﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.DataSourcesGDB;
using GGIS.基本功能;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using 地理信息系统开发教程;
using ESRI.ArcGIS.Output;
using stdole;
using GISEditor.EditTool.BasicClass;
using ESRI.ArcGIS.Geoprocessor;

namespace GGIS
{
    public partial class MainForm : Form
    {


        public MainForm()
        {
            InitializeComponent();
        }

        #region 定义变量

        //长度、面积量算
        private FormMeasureResult frmMeasureResult = null;   //量算结果窗体
        private INewLineFeedback pNewLineFeedback;           //追踪线对象
        private INewPolygonFeedback pNewPolygonFeedback;     //追踪面对象
        private IPoint pPointPt = null;                      //鼠标点击点
        private IPoint pMovePt = null;                       //鼠标移动时的当前点
        private double dToltalLength = 0;                    //量测总长度
        private double dSegmentLength = 0;                   //片段距离
        private IPointCollection pAreaPointCol = new MultipointClass();  //面积量算时画的点进行存储；

        private string sMapUnits = "未知单位";             //地图单位变量
        private object missing = Type.Missing;
        string pMouseOperate = null;

        //TOC菜单
        IFeatureLayer pTocFeatureLayer = null;            //点击的要素图层
        private FormAtrribute frmAttribute = null;        //图层属性窗体

        //查询
        private FormQueryByAttribute formQueryByAttribute = null; //属性查询界面
        private FormQueryBySpatial formQueryBySpatial = null;//空间查询界面

        //标注
        private frmAnnotation frmAnnotation = null;  // 注记
        private frmTextElement frmTextElement = null;//标注
        private frmMapTips frmMapTips = null;//MapTips
        private OperateMap m_OperateMap = null;

        //地图到处窗体                 
        private frmSymbol frmSym = null;
        private frmPrintPreview frmPrintPreview = null; // 打印

        //对地图的基本操作类
        private OperatePageLayout m_OperatePageLayout = null;
        private INewEnvelopeFeedback pNewEnvelopeFeedback;
        private EnumMapSurroundType _enumMapSurType = EnumMapSurroundType.None;
        private IStyleGalleryItem pStyleGalleryItem;
        private IPoint m_MovePt = null;
        private IPoint m_PointPt = null;
        private System.Drawing.Printing.PrintDocument document = new System.Drawing.Printing.PrintDocument(); //打印 
        string filepath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

        //专题地图
        private frmUniqueValueRender frmUniqueValueRen = null;
        private frmUniqueValueMany_fields frmUniqueValueMany_fields = null;
        private frmSimpleRender frmSimRender = null;
        //private frmChartRender frmChartRender = null;
        private frmDotDensity frmDotDensity = null;  // 点密度 
        private frmProportional frmProportional = null;//比例符号化
        //private frmGraduatedcolors frmGraduatedcolors = null; // 分级色彩
        private frmGraduatedSymbols frmGraduatedSymbols = null;// 分级符号      
        private frmBivariateRenderer frmBivariateRenderer = null; // 双值渲染
        private frmScaleDependentRenderer frmScaleDependentRenderer = null;//多比例尺渲染

        //对地图的基本操作类
        private EnumChartRenderType _enumChartType = EnumChartRenderType.UnKnown;

        //数据编辑
        private string sMxdPath = Application.StartupPath;
        private IMap pMap = null;
        private IActiveView pActiveView = null;
        private List<ILayer> plstLayers = null;
        private IFeatureLayer pCurrentLyr = null;
        private IEngineEditor pEngineEditor = null;
        private IEngineEditTask pEngineEditTask = null;
        private IEngineEditLayers pEngineEditLayers = null;

        #endregion
        #region 函数
        private void ClearAllData()
        {
            if (mainMapControl.Map != null && mainMapControl.Map.LayerCount > 0)
            {
                //新建mainMapControl中Map
                IMap dataMap = new MapClass();
                dataMap.Name = "Map";
                mainMapControl.DocumentFilename = string.Empty;//DocumentFilename为The filename of the last map document loaded into the control
                mainMapControl.Map = dataMap;


            }

        }
        #endregion

        #region 封装的方法

        /// <summary>
        /// 添加数据集
        /// </summary>
        /// <param name="_pWorkspace, mapControl"></param>
        /// <returns></returns>
        private void AddAllDataset(IWorkspace pWorkspace, AxMapControl mapControl)
        {
            IEnumDataset pEnumDataset = pWorkspace.get_Datasets(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTAny);
            pEnumDataset.Reset();
            //将Enum数据集中的数据一个个读到DataSet中
            IDataset pDataset = pEnumDataset.Next();
            //判断数据集是否有数据
            while (pDataset != null)
            {
                if (pDataset is IFeatureDataset)  //要素数据集
                {
                    IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace;
                    IFeatureDataset pFeatureDataset = pFeatureWorkspace.OpenFeatureDataset(pDataset.Name);
                    IEnumDataset pEnumDataset1 = pFeatureDataset.Subsets;
                    pEnumDataset1.Reset();
                    IGroupLayer pGroupLayer = new GroupLayerClass();
                    pGroupLayer.Name = pFeatureDataset.Name;
                    IDataset pDataset1 = pEnumDataset1.Next();
                    while (pDataset1 != null)
                    {
                        if (pDataset1 is IFeatureClass)  //要素类
                        {
                            IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                            pFeatureLayer.FeatureClass = pFeatureWorkspace.OpenFeatureClass(pDataset1.Name);
                            if (pFeatureLayer.FeatureClass != null)
                            {
                                pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName;
                                pGroupLayer.Add(pFeatureLayer);
                                mapControl.Map.AddLayer(pFeatureLayer);
                            }
                        }
                        pDataset1 = pEnumDataset1.Next();
                    }
                }
                else if (pDataset is IFeatureClass) //要素类
                {
                    IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace;
                    IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                    pFeatureLayer.FeatureClass = pFeatureWorkspace.OpenFeatureClass(pDataset.Name);

                    pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName;
                    mapControl.Map.AddLayer(pFeatureLayer);
                }
                else if (pDataset is IRasterDataset) //栅格数据集
                {
                    IRasterWorkspaceEx pRasterWorkspace = (IRasterWorkspaceEx)pWorkspace;
                    IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(pDataset.Name);
                    //影像金字塔判断与创建
                    IRasterPyramid3 pRasPyrmid;
                    pRasPyrmid = pRasterDataset as IRasterPyramid3;
                    if (pRasPyrmid != null)
                    {
                        if (!(pRasPyrmid.Present))
                        {
                            pRasPyrmid.Create(); //创建金字塔
                        }
                    }
                    IRasterLayer pRasterLayer = new RasterLayerClass();
                    pRasterLayer.CreateFromDataset(pRasterDataset);
                    ILayer pLayer = pRasterLayer as ILayer;
                    mapControl.AddLayer(pLayer, 0);
                }
                pDataset = pEnumDataset.Next();
            }

            mapControl.ActiveView.Refresh();
        }
        /// <summary>
        /// 获取地图单位
        /// </summary>
        /// <param name="_esriMapUnit"></param>
        /// <returns></returns>
        private string GetMapUnit(esriUnits _esriMapUnit)
        {
            string sMapUnits = string.Empty;
            switch (_esriMapUnit)
            {
                case esriUnits.esriCentimeters:
                    sMapUnits = "厘米";
                    break;
                case esriUnits.esriDecimalDegrees:
                    sMapUnits = "十进制";
                    break;
                case esriUnits.esriDecimeters:
                    sMapUnits = "分米";
                    break;
                case esriUnits.esriFeet:
                    sMapUnits = "尺";
                    break;
                case esriUnits.esriInches:
                    sMapUnits = "英寸";
                    break;
                case esriUnits.esriKilometers:
                    sMapUnits = "千米";
                    break;
                case esriUnits.esriMeters:
                    sMapUnits = "米";
                    break;
                case esriUnits.esriMiles:
                    sMapUnits = "英里";
                    break;
                case esriUnits.esriMillimeters:
                    sMapUnits = "毫米";
                    break;
                case esriUnits.esriNauticalMiles:
                    sMapUnits = "海里";
                    break;
                case esriUnits.esriPoints:
                    sMapUnits = "点";
                    break;
                case esriUnits.esriUnitsLast:
                    sMapUnits = "UnitsLast";
                    break;
                case esriUnits.esriUnknownUnits:
                    sMapUnits = "未知单位";
                    break;
                case esriUnits.esriYards:
                    sMapUnits = "码";
                    break;
                default:
                    break;
            }
            return sMapUnits;
        }

        #endregion

        #region 数据加载

        #region 地图文档
        //IMapControl接口，LoadMxFile方法加载
        private void loadMxFileToolStripMenuItem_Click(object sender, EventArgs e)
        {

            //.NET框架提供打开文件对话框
            //CheckMxFile方法检测地图有效性
            //LoadMxFile方法加载

            OpenFileDialog popenFileDialog = new OpenFileDialog();
            popenFileDialog.CheckFileExists = true;
            popenFileDialog.Title = "打开地图文档";
            popenFileDialog.Filter = "ArcMap文档(*.mxd)|*.mxd";

            popenFileDialog.Multiselect = false;    //不允许多个文件同时选择
            popenFileDialog.RestoreDirectory = true;    //储存打开文件路径

            if (popenFileDialog.ShowDialog() == DialogResult.OK)
            {
                string pFileName = popenFileDialog.FileName;
                if (pFileName == "")
                {
                    return;
                }

                if (mainMapControl.CheckMxFile(pFileName))  //检查地图文档有效性
                {
                    ClearAllData();
                    mainMapControl.LoadMxFile(pFileName);
                }

                else
                {
                    MessageBox.Show(pFileName + "是无效的地图文档！", "信息提醒");
                    return;
                }
            }

        }

        //IMapDocument接口加载
        private void iMapDocumentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog popenFileDialog = new OpenFileDialog();
            popenFileDialog.CheckFileExists = true;
            popenFileDialog.Title = "打开地图文档";
            popenFileDialog.Filter = "ArcMap文档(*.mxd)|*.mxd";

            popenFileDialog.Multiselect = false;    //不允许多个文件同时选择
            popenFileDialog.RestoreDirectory = true;    //储存打开文件路径

            if (popenFileDialog.ShowDialog() == DialogResult.OK)
            {
                string pFileName = popenFileDialog.FileName;
                if (pFileName == "")
                {
                    return;
                }
                if (mainMapControl.CheckMxFile(pFileName))  //检查地图文档有效性
                {
                    //将数据载入pMapDocument并与Map控件关联
                    //using ESRI.ArcGIS.Carto;

                    IMapDocument pMapDocument = new MapDocument();
                    pMapDocument.Open(pFileName, "");

                    //获取Map中激活的地图文档
                    mainMapControl.Map = pMapDocument.ActiveView.FocusMap;
                    mainMapControl.ActiveView.Refresh();
                }
                else
                {
                    MessageBox.Show(pFileName + "是无效的地图文档！", "信息提醒");
                    return;
                }
            }
        }


        //使用封装好的类库资源，ControlOpenDocCommandClass
        private void cODCCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsOpenDocCommandClass();
            command.OnCreate(mainMapControl.Object);
            command.OnClick();
        }
        #endregion

        #region Shapefile文件
        //通过工作空间工厂加载Shapefile文件
        private void workspaceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            pOpenFileDialog.CheckFileExists = true;
            pOpenFileDialog.Title = "打开Shape文件";
            pOpenFileDialog.Filter = "Shape文件(*.shp)|*.shp";
            pOpenFileDialog.ShowDialog();

            //获取文件路径
            //IWorkspaceFactory pWorkspaceFactory;
            //IFeatureWorkspace pFeatureWorkspace;
            //IFeatureLayer pFeatureLayer;

            string pFullName = pOpenFileDialog.FileName;
            if (pFullName == "")
            {
                return;
            }

            //解析文件名
            int pIndex = pFullName.LastIndexOf("\\");
            string pFilePath = pFullName.Substring(0, pIndex);  //文件路径
            string pFileName = pFullName.Substring(pIndex + 1); //文件名

            ////实例化ShapefileWorkspaceFactory工作空间，打开shapefile文件
            //pWorkspaceFactory = new ShapefileWorkspaceFactory();
            //pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(pFileName, 0);

            ////创建并实例化要素集

            //IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(pFileName);
            //pFeatureLayer = new FeatureLayer();
            //pFeatureLayer.FeatureClass = pFeatureClass;
            //pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName;

            //ClearAllData();     //删除所有已加载数据

            //mainMapControl.Map.AddLayer(pFeatureLayer);
            //mainMapControl.ActiveView.Refresh();

            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
            IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(pFilePath, 0);
            IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(pFileName);
            IFeatureLayer pFeatureLayer = new FeatureLayer();

            pFeatureLayer.FeatureClass = pFeatureClass;
            pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName;
            mainMapControl.Map.AddLayer(pFeatureLayer);
            mainMapControl.ActiveView.Refresh();




        }

        //通过MapControl
        private void addShapefileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            pOpenFileDialog.CheckFileExists = true;
            pOpenFileDialog.Title = "打开Shape文件";
            pOpenFileDialog.Filter = "Shape文件(*.shp)|*.shp";
            pOpenFileDialog.ShowDialog();

            string pFullName = pOpenFileDialog.FileName;
            if (pFullName == "")
            {
                return;
            }

            //解析文件名
            int pIndex = pFullName.LastIndexOf("\\");
            string pFilePath = pFullName.Substring(0, pIndex);  //文件路径
            string pFileName = pFullName.Substring(pIndex + 1); //文件名

            //加载
            mainMapControl.AddShapeFile(pFilePath, pFileName);
        }

        #endregion

        #region 栅格数据加载
        private void RasterDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            pOpenFileDialog.CheckFileExists = true;
            pOpenFileDialog.Title = "打开Raster文件";
            pOpenFileDialog.Filter = "栅格数据(*.*)|*.bmp;*.tif;*.jpg;*.img|(*.bmp)|*.bmp|(*.tif)|*.tif|(*.jpg)|*.jpg|(*.img)|*.img";
            pOpenFileDialog.ShowDialog();

            string pRasterFileName = pOpenFileDialog.FileName;
            if (pRasterFileName == "")
            {
                return;
            }

            string pPath = System.IO.Path.GetDirectoryName(pRasterFileName);
            string pFileName = System.IO.Path.GetFileName(pRasterFileName);

            IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory();
            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(pPath, 0);
            IRasterWorkspace pRasterWorkspace = pWorkspace as IRasterWorkspace;
            IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(pFileName);

            //影像金字判断与创建

            IRasterPyramid3 pRasPyrmid;
            pRasPyrmid = pRasterDataset as IRasterPyramid3;

            if (pRasPyrmid != null)
            {
                if (!(pRasPyrmid.Present))
                {
                    pRasPyrmid.Create();    //创建金字塔
                }
            }

            IRaster pRaster;
            pRaster = pRasterDataset.CreateDefaultRaster();
            IRasterLayer pRasterLayer;
            pRasterLayer = new RasterLayerClass();
            pRasterLayer.CreateFromRaster(pRaster);
            ILayer pLayer = pRasterLayer as ILayer;
            mainMapControl.AddLayer(pLayer, 0);
        }
        #endregion

        #region CAD数据加载
        //矢量方式加载
        private void CADVectorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            pOpenFileDialog.CheckFileExists = true;
            pOpenFileDialog.Title = "打开CAD文件";
            pOpenFileDialog.Filter = "CAD（*.dwg）|*.dwg";
            pOpenFileDialog.ShowDialog();

            string pFullPath = pOpenFileDialog.FileName;
            int pIndex = pFullPath.LastIndexOf("\\");


            string path = pFullPath.Substring(0, pIndex); //文件路径
            string filename = pFullPath.Substring(pIndex + 1); //文件名

            IWorkspaceFactory pCadWorkspaceFactory = new CadWorkspaceFactoryClass();
            IFeatureWorkspace pWorkspace = (IFeatureWorkspace)pCadWorkspaceFactory.OpenFromFile(path, 0);
            IFeatureDataset pFeatureDataset = pWorkspace.OpenFeatureDataset(filename);

            //IFeatureClassContainer可以管理IFeatureDataset中的每个要素类
            IFeatureClassContainer pFeatClassContainer = (IFeatureClassContainer)pFeatureDataset;

            //对CAD文件中的要素进行遍历处理
            for (int i = 0; i < pFeatClassContainer.ClassCount; i++)
            {
                IFeatureClass pFeatClass = pFeatClassContainer.get_Class(i);
                //如果是注记，则添加注记层
                if (pFeatClass.FeatureType == esriFeatureType.esriFTCoverageAnnotation)
                {
                    IFeatureLayer pFeatureLayer = new CadAnnotationLayerClass();
                    pFeatureLayer.Name = pFeatClass.AliasName;
                    pFeatureLayer.FeatureClass = pFeatClass;
                    mainMapControl.Map.AddLayer(pFeatureLayer);
                }
                else //如果是点、线、面则添加要素层
                {
                    IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                    pFeatureLayer.Name = pFeatClass.AliasName;
                    pFeatureLayer.FeatureClass = pFeatClass;
                    mainMapControl.Map.AddLayer(pFeatureLayer);
                }
                mainMapControl.ActiveView.Refresh();
            }
        }

        //栅格方式加载
        private void CADRasterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            pOpenFileDialog.CheckFileExists = true;
            pOpenFileDialog.Title = "打开CAD文件";
            pOpenFileDialog.Filter = "CAD（*.dwg）|*.dwg";
            pOpenFileDialog.ShowDialog();

            string pFullPath = pOpenFileDialog.FileName;
            int pIndex = pFullPath.LastIndexOf("\\");


            string path = pFullPath.Substring(0, pIndex); //文件路径
            string filename = pFullPath.Substring(pIndex + 1); //文件名

            IWorkspaceFactory pCadWorkspaceFactory = new CadWorkspaceFactoryClass();
            IWorkspace pWorkspace = pCadWorkspaceFactory.OpenFromFile(path, 0);
            ICadDrawingWorkspace pCadDrawingWorkspace = (ICadDrawingWorkspace)pWorkspace;

            ICadDrawingDataset pCadDrawingDataset = pCadDrawingWorkspace.OpenCadDrawingDataset(filename);
            ICadLayer pCadLayer = new CadLayerClass();
            pCadLayer.CadDrawingDataset = pCadDrawingDataset;
            mainMapControl.AddLayer(pCadLayer);
        }
        #endregion

        #region 地理数据库加载

        //个人地理数据库
        private void PersonToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog pOpenFileDialog = new OpenFileDialog();
            pOpenFileDialog.Filter = "Personal Geodatabase(*.mdb)|*.mdb";
            pOpenFileDialog.Title = "打开PersonGeodatabase文件";
            pOpenFileDialog.ShowDialog();

            string pFullPath = pOpenFileDialog.FileName;
            if (pFullPath == "")
            {
                return;
            }
            IWorkspaceFactory pAccessWorkspaceFactory = new AccessWorkspaceFactory(); //using ESRI.ArcGIS.DataSourcesGDB;
            //获取工作空间
            IWorkspace pWorkspace = pAccessWorkspaceFactory.OpenFromFile(pFullPath, 0);


            //加载工作空间里的数据
            AddAllDataset(pWorkspace, mainMapControl);
        }


        //文件地理数据库
        private void FileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IWorkspaceFactory pFileGDBWorkspaceFactory;

            FolderBrowserDialog dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() != DialogResult.OK) return;
            string pFullPath = dlg.SelectedPath;

            if (pFullPath == "")
            {
                return;
            }
            //using ESRI.ArcGIS.DataSourcesGDB;
            pFileGDBWorkspaceFactory = new FileGDBWorkspaceFactoryClass();

            //获取工作空间
            IWorkspace pWorkspace = pFileGDBWorkspaceFactory.OpenFromFile(pFullPath, 0);
            AddAllDataset(pWorkspace, mainMapControl);
        }
        #endregion

        #region 地图文档的保存与另存为
        //地图文档的保存
        private void MxdSaveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string sMxdFileName = mainMapControl.DocumentFilename;
                IMapDocument pMapDocument = new MapDocumentClass();

                if (sMxdFileName != null && mainMapControl.CheckMxFile(sMxdFileName))
                {
                    if (pMapDocument.get_IsReadOnly(sMxdFileName))
                    {
                        MessageBox.Show("本地图文档是只读的，不能保存！");
                        pMapDocument.Close();
                        return;
                    }
                }
                else
                {
                    SaveFileDialog pSaveFileDialog = new SaveFileDialog();
                    pSaveFileDialog.Title = "请选择保存路径";
                    pSaveFileDialog.OverwritePrompt = true;
                    pSaveFileDialog.Filter = "ArcMap文档(*.mxd)|*.mxd|ArcMap模板(*.mxt)|*.mxt";
                    pSaveFileDialog.RestoreDirectory = true;

                    if (pSaveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        sMxdFileName = pSaveFileDialog.FileName;
                    }
                    else
                    {
                        return;
                    }
                }

                pMapDocument.New(sMxdFileName);
                pMapDocument.ReplaceContents(mainMapControl.Map as IMxdContents);
                pMapDocument.Save(pMapDocument.UsesRelativePaths, true);
                pMapDocument.Close();
                MessageBox.Show("保存文档成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }



        }
        //地图文档另存为
        private void MxdSaveOtherToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsSaveAsDocCommandClass();
            command.OnCreate(mainMapControl.Object);
            command.OnClick();
        }
        #endregion

        #endregion

        #region 地图浏览
        //全图显示
        private void FulloolStripMenuItem_Click(object sender, EventArgs e)
        {
            mainMapControl.Extent = mainMapControl.FullExtent;
        }
        #endregion

        #region ICommand和ITools命令
        //前一视图
        private void PreViewMenuItem_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsMapZoomToLastExtentBackCommand();
            command.OnCreate(mainMapControl.Object);
            command.OnClick();
        }
        //后一视图
        private void NextExtentMenuItem_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsMapZoomToLastExtentForwardCommand();
            command.OnCreate(mainMapControl.Object);
            command.OnClick();
        }
        //全屏显示
        private void FullMenuItem_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsFullScreenCommand();
            command.OnCreate(mainMapControl.Object);
            command.OnClick();
        }
        //要素清楚选择
        private void ClearFeatureMenuItem_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsClearSelectionCommand();
            command.OnCreate(mainMapControl.Object);
            command.OnClick();
        }
        //量测
        private void MeasureMenuItem_Click(object sender, EventArgs e)
        {
            mainMapControl.CurrentTool = null;
            ControlsMapMeasureTool tool = new ControlsMapMeasureToolClass();
            tool.OnCreate(mainMapControl.Object);
            mainMapControl.CurrentTool = tool as ITool;
        }

        //要素选择
        private void ChoseMenuItem_Click(object sender, EventArgs e)
        {
            mainMapControl.CurrentTool = null;
            ControlsSelectFeaturesTool tool = new ControlsSelectFeaturesTool();
            tool.OnCreate(mainMapControl.Object);
            mainMapControl.CurrentTool = tool as ITool;
        }

        #endregion

        #region 量测
        //距离量测
        private void DistanceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mainMapControl.CurrentTool = null;
            pMouseOperate = "MeasureLength";
            mainMapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
            if (frmMeasureResult == null || frmMeasureResult.IsDisposed)
            {
                frmMeasureResult = new FormMeasureResult();
                frmMeasureResult.frmClosed += new FormMeasureResult.FormClosedEventHandler(frmMeasureResult_frmColsed);
                frmMeasureResult.lblMeasureResult.Text = "";
                frmMeasureResult.Text = "距离量测";
                frmMeasureResult.Show();
            }
            else
            {
                frmMeasureResult.Activate();
            }
        }

        //面积量测
        private void AreaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mainMapControl.CurrentTool = null;
            pMouseOperate = "MeasureArea";
            mainMapControl.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
            if (frmMeasureResult == null || frmMeasureResult.IsDisposed)
            {
                frmMeasureResult = new FormMeasureResult();
                frmMeasureResult.frmClosed += new FormMeasureResult.FormClosedEventHandler(frmMeasureResult_frmColsed);
                frmMeasureResult.lblMeasureResult.Text = "";
                frmMeasureResult.Text = "面积量测";
                frmMeasureResult.Show();
            }
            else
            {
                frmMeasureResult.Activate();
            }
        }

        //测量结果窗口关闭响应事件
        private void frmMeasureResult_frmColsed()
        {
            //清空线对象
            if (pNewLineFeedback != null)
            {
                pNewLineFeedback.Stop();
                pNewLineFeedback = null;
            }
            //清空面对象
            if (pNewPolygonFeedback != null)
            {
                pNewPolygonFeedback.Stop();
                pNewPolygonFeedback = null;
                pAreaPointCol.RemovePoints(0, pAreaPointCol.PointCount); //清空点集中所有点
            }
            //清空量算画的线、面对象
            mainMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewForeground, null, null);
            //结束量算功能
            pMouseOperate = string.Empty;
            mainMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
        }
        #endregion

        #region mainmapcontrol事件
        private void mainMapControl_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            sMapUnits = GetMapUnit(mainMapControl.Map.MapUnits);
            Label1.Text = String.Format("当前坐标：X = {0:#.###} Y = {1:#.###} {2}", e.mapX, e.mapY, sMapUnits);
            pMovePt = (mainMapControl.Map as IActiveView).ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);

            #region 长度量算
            if (pMouseOperate == "MeasureLength")
            {
                if (pNewLineFeedback != null)
                {
                    pNewLineFeedback.MoveTo(pMovePt);
                }
                double deltaX = 0; //两点之间X差值
                double deltaY = 0; //两点之间Y差值

                if ((pPointPt != null) && (pNewLineFeedback != null))
                {
                    deltaX = pMovePt.X - pPointPt.X;
                    deltaY = pMovePt.Y - pPointPt.Y;
                    dSegmentLength = Math.Round(Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY)), 3);
                    dToltalLength = dToltalLength + dSegmentLength;
                    if (frmMeasureResult != null)
                    {
                        frmMeasureResult.lblMeasureResult.Text = String.Format(
                            "当前线段长度：{0:.###}{1};\r\n总长度为: {2:.###}{1}",
                            dSegmentLength, sMapUnits, dToltalLength);
                        dToltalLength = dToltalLength - dSegmentLength; //鼠标移动到新点重新开始计算
                    }
                    frmMeasureResult.frmClosed += new FormMeasureResult.FormClosedEventHandler(frmMeasureResult_frmColsed);
                }
            }
            #endregion

            #region 面积量算
            if (pMouseOperate == "MeasureArea")
            {
                if (pNewPolygonFeedback != null)
                {
                    pNewPolygonFeedback.MoveTo(pMovePt);
                }

                IPointCollection pPointCol = new Polygon();
                IPolygon pPolygon = new PolygonClass();
                IGeometry pGeo = null;

                ITopologicalOperator pTopo = null;
                for (int i = 0; i <= pAreaPointCol.PointCount - 1; i++)
                {
                    pPointCol.AddPoint(pAreaPointCol.get_Point(i), ref missing, ref missing);
                }
                pPointCol.AddPoint(pMovePt, ref missing, ref missing);

                if (pPointCol.PointCount < 3) return;
                pPolygon = pPointCol as IPolygon;

                if ((pPolygon != null))
                {
                    pPolygon.Close();
                    pGeo = pPolygon as IGeometry;
                    pTopo = pGeo as ITopologicalOperator;
                    //使几何图形的拓扑正确
                    pTopo.Simplify();
                    pGeo.Project(mainMapControl.Map.SpatialReference);
                    IArea pArea = pGeo as IArea;

                    frmMeasureResult.lblMeasureResult.Text = String.Format(
                        "总面积为：{0:.####}平方{1};\r\n总长度为：{2:.####}{1}",
                        pArea.Area, sMapUnits, pPolygon.Length);
                    pPolygon = null;
                }
            }
            #endregion
        }

        private void mainMapControl_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            //屏幕坐标点转化为地图坐标点
            pPointPt = (mainMapControl.Map as IActiveView).ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);

            if (e.button == 1)
            {
                IActiveView pActiveView = mainMapControl.ActiveView;
                IEnvelope pEnvelope = new EnvelopeClass();

                switch (pMouseOperate)
                {
                    #region 距离量算
                    case "MeasureLength":
                        //判断追踪线对象是否为空，若是则实例化并设置当前鼠标点为起始点
                        if (pNewLineFeedback == null)
                        {
                            //实例化追踪线对象
                            pNewLineFeedback = new NewLineFeedbackClass();
                            pNewLineFeedback.Display = (mainMapControl.Map as IActiveView).ScreenDisplay;
                            //设置起点，开始动态线绘制
                            pNewLineFeedback.Start(pPointPt);
                            dToltalLength = 0;
                        }
                        else //如果追踪线对象不为空，则添加当前鼠标点
                        {
                            pNewLineFeedback.AddPoint(pPointPt);
                        }
                        //pGeometry = m_PointPt;
                        if (dSegmentLength != 0)
                        {
                            dToltalLength = dToltalLength + dSegmentLength;
                        }
                        break;
                    #endregion

                    #region 面积量算
                    case "MeasureArea":
                        if (pNewPolygonFeedback == null)
                        {
                            //实例化追踪面对象
                            pNewPolygonFeedback = new NewPolygonFeedback();
                            pNewPolygonFeedback.Display = (mainMapControl.Map as IActiveView).ScreenDisplay;
                            ;
                            pAreaPointCol.RemovePoints(0, pAreaPointCol.PointCount);
                            //开始绘制多边形
                            pNewPolygonFeedback.Start(pPointPt);
                            pAreaPointCol.AddPoint(pPointPt, ref missing, ref missing);
                        }
                        else
                        {
                            pNewPolygonFeedback.AddPoint(pPointPt);
                            pAreaPointCol.AddPoint(pPointPt, ref missing, ref missing);
                        }
                        break;
                    #endregion

                    default:
                        break;
                }
            }
            else if (e.button == 2)
            {
                pMouseOperate = "";
                mainMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
            }
        }


        #endregion

        #region 视图同步
        private void mainMapControl_OnAfterScreenDraw(object sender, IMapControlEvents2_OnAfterScreenDrawEvent e)
        {
            IActiveView pActiveView = (IActiveView)PageLayoutControl_1.ActiveView.FocusMap;
            IDisplayTransformation displayTransformation = pActiveView.ScreenDisplay.DisplayTransformation;
            displayTransformation.VisibleBounds = mainMapControl.Extent;
            PageLayoutControl_1.ActiveView.Refresh();
            CopyToPageLayout();
        }

        private void CopyToPageLayout()
        {
            IObjectCopy pObjectCopy = new ObjectCopyClass();
            object copyFromMap = mainMapControl.Map;
            object copiedMap = pObjectCopy.Copy(copyFromMap);//复制地图到copiedMap中
            object copyToMap = PageLayoutControl_1.ActiveView.FocusMap;
            pObjectCopy.Overwrite(copiedMap, copyToMap); //复制地图
            PageLayoutControl_1.ActiveView.Refresh();
        }
        #endregion

        #region mainmapcontrl事件2
        //量测需双击
        private void mainMapControl_OnDoubleClick(object sender, IMapControlEvents2_OnDoubleClickEvent e)
        {
            #region 长度量算
            if (pMouseOperate == "MeasureLength")
            {
                if (frmMeasureResult != null)
                {
                    frmMeasureResult.lblMeasureResult.Text = "线段总长度为：" + dToltalLength + sMapUnits;
                }
                if (pNewLineFeedback != null)
                {
                    pNewLineFeedback.Stop();
                    pNewLineFeedback = null;
                    //清空所画的线对象
                    (mainMapControl.Map as IActiveView).PartialRefresh(esriViewDrawPhase.esriViewForeground, null, null);
                }
                dToltalLength = 0;
                dSegmentLength = 0;
            }
            #endregion

            #region 面积量算
            if (pMouseOperate == "MeasureArea")
            {
                if (pNewPolygonFeedback != null)
                {
                    pNewPolygonFeedback.Stop();
                    pNewPolygonFeedback = null;
                    //清空所画的线对象
                    (mainMapControl.Map as IActiveView).PartialRefresh(esriViewDrawPhase.esriViewForeground, null, null);
                }
                pAreaPointCol.RemovePoints(0, pAreaPointCol.PointCount); //清空点集中所有点
            }
            #endregion
        }
        #endregion


        #region TOC左键功能及右键菜单
        private ESRI.ArcGIS.Geometry.Point pMoveLayerPoint = new ESRI.ArcGIS.Geometry.Point();  //鼠标在TOC中左键按下时点的位置
                                                                                                //TOC右键菜单的添加
        private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {
            try
            {
                esriTOCControlItem pItem = esriTOCControlItem.esriTOCControlItemNone;
                IBasicMap pMap = null;
                ILayer pLayer = null;
                object unk = null;
                object data = null;
                axTOCControl1.HitTest(e.x, e.y, ref pItem, ref pMap, ref pLayer, ref unk, ref data);
                if (e.button == 2)
                {
                    pTocFeatureLayer = pLayer as IFeatureLayer;
                    if (pItem == esriTOCControlItem.esriTOCControlItemLayer && pTocFeatureLayer != null)
                    {
                        btnLayerSel.Enabled = !pTocFeatureLayer.Selectable;
                        btnLayerUnsel.Enabled = pTocFeatureLayer.Selectable;
                        contextMenuStrip1.Show(Control.MousePosition);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void axTOCControl1_OnDoubleClick(object sender, ITOCControlEvents_OnDoubleClickEvent e)
        {
            esriTOCControlItem pItem = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap pMap = null;
            ILayer pLayer = null;
            object unk = null;
            object data = null;
            axTOCControl1.HitTest(e.x, e.y, ref pItem, ref pMap, ref pLayer, ref unk, ref data);
            if (e.button == 1)
            {
                if (pItem == esriTOCControlItem.esriTOCControlItemLegendClass)
                {
                    //取得图例
                    ILegendClass pLegendClass = ((ILegendGroup)unk).get_Class((int)data);
                    //创建符号选择器SymbolSelector实例
                    frmSymbolSelector SymbolSelectorFrm = new frmSymbolSelector(pLegendClass, pLayer);
                    if (SymbolSelectorFrm.ShowDialog() == DialogResult.OK)
                    {
                        //局部更新主Map控件
                        mainMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                        //设置新的符号
                        pLegendClass.Symbol = SymbolSelectorFrm.pSymbol;
                        //更新主Map控件和图层控件
                        this.mainMapControl.ActiveView.Refresh();
                        this.axTOCControl1.Refresh();
                    }
                }
            }
        }

        //TOCC属性表
        private void btnAttribute_Click(object sender, EventArgs e)
        {
            if (frmAttribute == null || frmAttribute.IsDisposed)
            {
                frmAttribute = new FormAtrribute();
            }
            frmAttribute.CurFeatureLayer = pTocFeatureLayer;
            frmAttribute.InitUI();
            frmAttribute.Show();
        }

        //缩放至图层
        private void btnZoomToLayer_Click(object sender, EventArgs e)
        {
            if (pTocFeatureLayer == null) return;
            (mainMapControl.Map as IActiveView).Extent = pTocFeatureLayer.AreaOfInterest;
            (mainMapControl.Map as IActiveView).PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
        }

        //移除图层
        private void btnRemoveLayer_Click(object sender, EventArgs e)
        {
            try
            {
                if (pTocFeatureLayer == null) return;
                DialogResult result = MessageBox.Show("是否删除[" + pTocFeatureLayer.Name + "]图层", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    mainMapControl.Map.DeleteLayer(pTocFeatureLayer);
                }
                mainMapControl.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //图层可选
        private void btnLayerSel_Click(object sender, EventArgs e)
        {
            pTocFeatureLayer.Selectable = true;
            btnLayerSel.Enabled = !btnLayerSel.Enabled;
        }

        //图层不可选
        private void btnLayerUnsel_Click(object sender, EventArgs e)
        {
            pTocFeatureLayer.Selectable = false;
            btnLayerUnsel.Enabled = !btnLayerUnsel.Enabled;
        }
        #endregion

        #region 查询
        //属性查询
        private void AttributeQuery_Click(object sender, EventArgs e)
        {
            if (formQueryByAttribute == null || formQueryByAttribute.IsDisposed)
            {
                //新创建属性查询窗体
                formQueryByAttribute = new FormQueryByAttribute();
                //将当前主窗体中MapControl控件中的Map对象赋值给FormQueryByAttribute窗体的CurrentMap属性
                formQueryByAttribute.CurrentMap = mainMapControl.Map;
                //显示属性查询窗体
                formQueryByAttribute.Show();
            }
            else
            {
                formQueryByAttribute.Activate();
            }
        }

        //空间查询
        private void SpatialQuery_Click(object sender, EventArgs e)
        {
            if (formQueryBySpatial == null || formQueryBySpatial.IsDisposed)
            {
                //新创建空间查询窗体
                formQueryBySpatial = new FormQueryBySpatial();
                //将当前主窗体中MapControl控件中的Map对象赋值给FormSelection窗体的CurrentMap属性
                formQueryBySpatial.CurrentMap = mainMapControl.Map;
                //显示空间查询窗体
                formQueryBySpatial.Show();
            }
            else
            {
                formQueryBySpatial.Activate();
            }
        }

        private void SelectionSet_Click(object sender, EventArgs e)
        {
            //新创建地图选择集窗体
            FormSelection formSelection = new FormSelection();
            //将当前主窗体中MapControl控件中的Map对象赋值给FormSelection窗体的CurrentMap属性
            formSelection.CurrentMap = mainMapControl.Map;
            //显示地图选择集窗体
            formSelection.Show();
        }
        #endregion

        #region 标注
        #region TextElement标注
        private void txtElement_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmTextElement == null || frmTextElement.IsDisposed)
                {
                    frmTextElement = new frmTextElement();
                    frmTextElement.TextElement += new frmTextElement.TextElementLabelEventHandler(frmTextElement_TextElement);
                }
                frmTextElement.Map = mainMapControl.Map;
                frmTextElement.InitUI();
                frmTextElement.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void frmTextElement_TextElement(string sFeatClsName, string sFieldName)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            TextElementLabel(pFeatLyr, sFieldName);
        }

        private void TextElementLabel(IFeatureLayer pFeatLyr, string sFieldName)
        {
            try
            {
                IMap pMap = mainMapControl.Map;
                //获得图层所有要素
                IFeatureClass pFeatureClass = pFeatLyr.FeatureClass;
                IFeatureCursor pFeatCursor = pFeatureClass.Search(null, true);
                IFeature pFeature = pFeatCursor.NextFeature();
                while (pFeature != null)
                {
                    IFields pFields = pFeature.Fields;
                    //找出标注字段的索引号
                    int index = pFields.FindField(sFieldName);
                    //得到要素的Envelope
                    IEnvelope pEnve = pFeature.Extent;
                    IPoint pPoint = new PointClass();
                    pPoint.PutCoords(pEnve.XMin + pEnve.Width / 2, pEnve.YMin + pEnve.Height / 2);
                    //新建字体对象
                    stdole.IFontDisp pFont;
                    pFont = new stdole.StdFontClass() as stdole.IFontDisp;
                    pFont.Name = "arial";
                    //产生一个文本符号
                    ITextSymbol pTextSymbol = new TextSymbolClass();
                    //设置文本符号的大小
                    pTextSymbol.Size = 20;
                    pTextSymbol.Font = pFont;
                    pTextSymbol.Color = m_OperateMap.GetRgbColor(255, 0, 0);
                    //产生一个文本对象
                    ITextElement pTextElement = new TextElementClass();
                    pTextElement.Text = pFeature.get_Value(index).ToString();
                    pTextElement.ScaleText = true;
                    pTextElement.Symbol = pTextSymbol;
                    IElement pElement = pTextElement as IElement;
                    pElement.Geometry = pPoint;
                    IActiveView pActiveView = pMap as IActiveView;
                    IGraphicsContainer pGraphicsContainer = pMap as IGraphicsContainer;
                    //添加元素
                    pGraphicsContainer.AddElement(pElement, 0);
                    pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                    pPoint = null;
                    pElement = null;
                    pFeature = pFeatCursor.NextFeature();
                }
            }
            catch (Exception ex)
            {

            }

        }
        #endregion

        //Annotation注记
        private void txtAnnotation_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmAnnotation == null || frmAnnotation.IsDisposed)
                {
                    frmAnnotation = new frmAnnotation();
                    frmAnnotation.Annotation += new frmAnnotation.AnnotationEventHandler(frmAnnotation_Annotation);
                }
                frmAnnotation.Map = mainMapControl.Map;
                frmAnnotation.InitUI();
                frmAnnotation.ShowDialog();
            }
            catch (Exception ex)
            {
            }
        }
        //注记
        void frmAnnotation_Annotation(string sFeatClsName, string sFieldName)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            Annotation(pFeatLyr, sFieldName);
        }
        /// <summary>
        /// 注记
        /// </summary>
        /// <param name="pFeatLyr">注记图层名称</param>
        /// <param name="sFieldName">注记字段</param>
        private void Annotation(IFeatureLayer pFeatLyr, string sFieldName)
        {
            try
            {
                IGeoFeatureLayer pGeoFeatLyer = pFeatLyr as IGeoFeatureLayer;
                IAnnotateLayerPropertiesCollection pAnnoProps = pGeoFeatLyer.AnnotationProperties;
                pAnnoProps.Clear();
                //设置标注记体格式                                                                     
                ITextSymbol pTextSymbol = new TextSymbolClass();
                stdole.StdFont pFont = new stdole.StdFontClass();
                pFont.Name = "verdana";
                pFont.Size = 10;
                pTextSymbol.Font = pFont as stdole.IFontDisp;
                //设置注记放置格式
                ILineLabelPosition pPosition = new LineLabelPositionClass();
                pPosition.Parallel = false;
                pPosition.Perpendicular = true;
                ILineLabelPlacementPriorities pPlacement = new LineLabelPlacementPrioritiesClass();
                IBasicOverposterLayerProperties pBasic = new BasicOverposterLayerPropertiesClass();
                pBasic.FeatureType = esriBasicOverposterFeatureType.esriOverposterPolyline;
                pBasic.LineLabelPlacementPriorities = pPlacement;//设置标注文本摆设路径权重
                pBasic.LineLabelPosition = pPosition;//控制文本的排放位置
                ILabelEngineLayerProperties pLableEngine = new LabelEngineLayerPropertiesClass();
                pLableEngine.Symbol = pTextSymbol;
                pLableEngine.BasicOverposterLayerProperties = pBasic;//设置标注文本的放置方式，以及处理文字间冲突的处理方式等
                pLableEngine.Expression = "[" + sFieldName + "]";//输入VBScript或JavaScript语言，设置要标注的字段
                IAnnotateLayerProperties pAnnoLayerProps = pLableEngine as IAnnotateLayerProperties;
                pAnnoProps.Add(pAnnoLayerProps);
                pGeoFeatLyer.DisplayAnnotation = true;
                mainMapControl.Refresh(esriViewDrawPhase.esriViewBackground, null, null);
                mainMapControl.Update();
            }
            catch (Exception ex)
            {

            }
        }

        private void txtmapTips_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmMapTips == null || frmMapTips.IsDisposed)
                {
                    frmMapTips = new frmMapTips();
                    frmMapTips.MapTips += new frmMapTips.MapTipsEventHandler(frmMapTips_MapTips);
                }
                frmMapTips.Map = mainMapControl.Map;
                frmMapTips.InitUI();
                frmMapTips.ShowDialog();
            }
            catch (Exception ex)
            {
            }
        }
        void frmMapTips_MapTips(string sFeatClsName, string sFieldName)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            for (int i = 0; i < mainMapControl.LayerCount; i++)
            {
                ILayer pLayers = mainMapControl.get_Layer(i);
                IFeatureLayer pFeatLyrs = pLayers as IFeatureLayer;
                pFeatLyrs.DisplayField = null;
            }
            MapTips(pFeatLyr, sFieldName);
        }
        /// <summary>
        /// MapTips显示
        /// </summary>
        /// <param name="pFeatLyr"></param>
        /// <param name="sFieldName"></param>
        private void MapTips(IFeatureLayer pFeatLyr, string sFieldName)
        {
            ILayer pLayer = new FeatureLayerClass();
            pLayer = pFeatLyr;
            pLayer.ShowTips = true;
            ILayerFields pLayerFields = (ILayerFields)pFeatLyr;
            for (int i = 0; i <= pLayerFields.FieldCount - 1; i++)
            {
                IField field = pLayerFields.get_Field(i);
                if (field.Name == sFieldName)
                {
                    pFeatLyr.DisplayField = field.Name;
                    break;
                }
            }
            mainMapControl.ShowMapTips = true;
        }
        #endregion

        #region 制图输出
        //打印
        private void printMenu_Click(object sender, EventArgs e)
        {
            frmPrintPreview = new frmPrintPreview(PageLayoutControl_1);
            frmPrintPreview.ShowDialog();
        }

        private void ExportMenu_Click(object sender, EventArgs e)
        {
            ExportMapToImage();
        }
        private void ExportMapToImage()
        {
            try
            {
                SaveFileDialog pSaveDialog = new SaveFileDialog();
                pSaveDialog.FileName = "";
                pSaveDialog.Filter = "JPG图片(*.JPG)|*.jpg|tif图片(*.tif)|*.tif|PDF文档(*.PDF)|*.pdf";
                if (pSaveDialog.ShowDialog() == DialogResult.OK)
                {
                    double iScreenDispalyResolution = PageLayoutControl_1.ActiveView.ScreenDisplay.DisplayTransformation.Resolution;// 获取屏幕分辨率的值
                    IExporter pExporter = null;
                    if (pSaveDialog.FilterIndex == 1)
                    {
                        pExporter = new JpegExporterClass();
                    }
                    else if (pSaveDialog.FilterIndex == 2)
                    {
                        pExporter = new TiffExporterClass();
                    }
                    else if (pSaveDialog.FilterIndex == 3)
                    {
                        pExporter = new PDFExporterClass();
                    }
                    pExporter.ExportFileName = pSaveDialog.FileName;
                    pExporter.Resolution = (short)iScreenDispalyResolution; //分辨率
                    tagRECT deviceRect = PageLayoutControl_1.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame();
                    IEnvelope pDeviceEnvelope = new EnvelopeClass();
                    pDeviceEnvelope.PutCoords(deviceRect.left, deviceRect.bottom, deviceRect.right, deviceRect.top);
                    pExporter.PixelBounds = pDeviceEnvelope; // 输出图片的范围
                    ITrackCancel pCancle = new CancelTrackerClass();//可用ESC键取消操作
                    PageLayoutControl_1.ActiveView.Output(pExporter.StartExporting(), pExporter.Resolution, ref deviceRect, PageLayoutControl_1.ActiveView.Extent, pCancle);
                    Application.DoEvents();
                    pExporter.FinishExporting();
                }

            }
            catch (Exception Err)
            {
                MessageBox.Show(Err.Message, "输出图片", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        #endregion

        #region 地图整饬
        //添加图例
        private void AddLegend_Click(object sender, EventArgs e)
        {
            try
            {
                _enumMapSurType = EnumMapSurroundType.Legend;
            }
            catch (Exception ex)
            {

            }
        }
        private void frmSym_GetSelSymbolItem(ref IStyleGalleryItem pStyleItem)
        {
            pStyleGalleryItem = pStyleItem;
        }

        //添加指北针
        private void AddNorthArrows_Click(object sender, EventArgs e)
        {
            try
            {
                _enumMapSurType = EnumMapSurroundType.NorthArrow;
                if (frmSym == null || frmSym.IsDisposed)
                {
                    frmSym = new frmSymbol();
                    frmSym.GetSelSymbolItem += new frmSymbol.GetSelSymbolItemEventHandler(frmSym_GetSelSymbolItem);
                }
                frmSym.EnumMapSurType = _enumMapSurType;
                frmSym.InitUI();
                frmSym.ShowDialog();
            }
            catch (Exception ex)
            {
            }
        }

        //添加比例尺
        private void AddScaleBar_Click(object sender, EventArgs e)
        {
            try
            {
                _enumMapSurType = EnumMapSurroundType.ScaleBar;
                if (frmSym == null || frmSym.IsDisposed)
                {
                    frmSym = new frmSymbol();
                    frmSym.GetSelSymbolItem += new frmSymbol.GetSelSymbolItemEventHandler(frmSym_GetSelSymbolItem);
                }
                frmSym.EnumMapSurType = _enumMapSurType;
                frmSym.InitUI();
                frmSym.ShowDialog();
            }
            catch (Exception ex)
            {
            }
        }
        #endregion

        #region 地图整饬和其他
        //通过OnMouseDown事件，产生矩形框的第一个点
        private void PageLayoutControl_1_OnMouseDown(object sender, IPageLayoutControlEvents_OnMouseDownEvent e)
        {
            try
            {
                if (_enumMapSurType != EnumMapSurroundType.None)
                {
                    IActiveView pActiveView = null;
                    pActiveView = PageLayoutControl_1.PageLayout as IActiveView;
                    m_PointPt = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                    if (pNewEnvelopeFeedback == null)
                    {
                        pNewEnvelopeFeedback = new NewEnvelopeFeedbackClass();
                        pNewEnvelopeFeedback.Display = pActiveView.ScreenDisplay;
                        pNewEnvelopeFeedback.Start(m_PointPt);
                    }
                    else
                    {
                        pNewEnvelopeFeedback.MoveTo(m_PointPt);
                    }

                }
            }
            catch
            {
            }
        }

        private void PageLayoutControl_1_OnMouseMove(object sender, IPageLayoutControlEvents_OnMouseMoveEvent e)
        {
            try
            {
                if (_enumMapSurType != EnumMapSurroundType.None)
                {
                    if (pNewEnvelopeFeedback != null)
                    {
                        m_MovePt = (PageLayoutControl_1.PageLayout as IActiveView).ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                        pNewEnvelopeFeedback.MoveTo(m_MovePt);
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
        //通过OnMouseUp事件，产生矩形框的第一个点的对焦点，返回一个矩形，并将制图要素添加到该矩形中
        private void PageLayoutControl_1_OnMouseUp(object sender, IPageLayoutControlEvents_OnMouseUpEvent e)
        {
            if (_enumMapSurType != EnumMapSurroundType.None)
            {
                if (pNewEnvelopeFeedback != null)
                {
                    IActiveView pActiveView = null;
                    pActiveView = PageLayoutControl_1.PageLayout as IActiveView;
                    IEnvelope pEnvelope = pNewEnvelopeFeedback.Stop();
                    AddMapSurround(pActiveView, _enumMapSurType, pEnvelope);
                    pNewEnvelopeFeedback = null;
                    _enumMapSurType = EnumMapSurroundType.None;
                }
            }
        }
        /// <summary>
        /// 添加地图整饰要素
        /// </summary>
        /// <param name="pAV"></param>
        /// <param name="_enumMapSurroundType"></param>
        /// <param name="pEnvelope"></param>
        private void AddMapSurround(IActiveView pAV, EnumMapSurroundType _enumMapSurroundType, IEnvelope pEnvelope)
        {
            try
            {
                switch (_enumMapSurroundType)
                {
                    case EnumMapSurroundType.NorthArrow:
                        addNorthArrow(PageLayoutControl_1.PageLayout, pEnvelope, pAV);
                        break;
                    case EnumMapSurroundType.ScaleBar:
                        makeScaleBar(pAV, PageLayoutControl_1.PageLayout, pEnvelope);
                        break;
                    case EnumMapSurroundType.Legend:
                        MakeLegend(pAV, PageLayoutControl_1.PageLayout, pEnvelope);
                        break;
                }
            }
            catch (Exception ex)
            {
            }
        }

        #region 添加图例
        /// <summary>
        /// 添加图例
        /// </summary>
        /// <param name="activeView"></活动窗口>
        /// <param name="pageLayout"></布局窗口>
        /// <param name="pEnv"></包络线>
        private void MakeLegend(IActiveView pActiveView, IPageLayout pPageLayout, IEnvelope pEnv)
        {
            UID pID = new UID();
            pID.Value = "esriCarto.Legend";
            IGraphicsContainer pGraphicsContainer = pPageLayout as IGraphicsContainer;
            IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pActiveView.FocusMap) as IMapFrame;
            IMapSurroundFrame pMapSurroundFrame = pMapFrame.CreateSurroundFrame(pID, null);//根据唯一标示符，创建与之对应MapSurroundFrame
            IElement pDeletElement = PageLayoutControl_1.FindElementByName("Legend");//获取PageLayout中的图例元素
            if (pDeletElement != null)
            {
                pGraphicsContainer.DeleteElement(pDeletElement);  //如果已经存在图例，删除已经存在的图例
            }
            //设置MapSurroundFrame背景
            ISymbolBackground pSymbolBackground = new SymbolBackgroundClass();
            IFillSymbol pFillSymbol = new SimpleFillSymbolClass();
            ILineSymbol pLineSymbol = new SimpleLineSymbolClass();
            pLineSymbol.Color = m_OperatePageLayout.GetRgbColor(0, 0, 0);
            pFillSymbol.Color = m_OperatePageLayout.GetRgbColor(240, 240, 240);
            pFillSymbol.Outline = pLineSymbol;
            pSymbolBackground.FillSymbol = pFillSymbol;
            pMapSurroundFrame.Background = pSymbolBackground;
            //添加图例
            IElement pElement = pMapSurroundFrame as IElement;
            pElement.Geometry = pEnv as IGeometry;
            IMapSurround pMapSurround = pMapSurroundFrame.MapSurround;
            ILegend pLegend = pMapSurround as ILegend;
            pLegend.ClearItems();
            pLegend.Title = "图例";
            for (int i = 0; i < pActiveView.FocusMap.LayerCount; i++)
            {
                ILegendItem pLegendItem = new HorizontalLegendItemClass();
                pLegendItem.Layer = pActiveView.FocusMap.get_Layer(i);//获取添加图例关联图层             
                pLegendItem.ShowDescriptions = false;
                pLegendItem.Columns = 1;
                pLegendItem.ShowHeading = true;
                pLegendItem.ShowLabels = true;
                pLegend.AddItem(pLegendItem);//添加图例内容
            }
            pGraphicsContainer.AddElement(pElement, 0);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }
        #endregion
        #region 指北针
        /// <summary>
        /// 插入指北针
        /// </summary>
        /// <param name="pPageLayout"></param>
        /// <param name="pEnv"></param>
        /// <param name="pActiveView"></param>
        void addNorthArrow(IPageLayout pPageLayout, IEnvelope pEnv, IActiveView pActiveView)
        {
            IMap pMap = pActiveView.FocusMap;
            IGraphicsContainer pGraphicsContainer = pPageLayout as IGraphicsContainer;
            IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;
            if (pStyleGalleryItem == null) return;
            IMapSurroundFrame pMapSurroundFrame = new MapSurroundFrameClass();
            pMapSurroundFrame.MapFrame = pMapFrame;
            INorthArrow pNorthArrow = new MarkerNorthArrowClass();
            pNorthArrow = pStyleGalleryItem.Item as INorthArrow;
            pNorthArrow.Size = pEnv.Width * 50;
            pMapSurroundFrame.MapSurround = (IMapSurround)pNorthArrow;//根据用户的选取，获取相应的MapSurround            
            IElement pElement = PageLayoutControl_1.FindElementByName("NorthArrows");//获取PageLayout中的指北针元素
            if (pElement != null)
            {
                pGraphicsContainer.DeleteElement(pElement);  //如果存在指北针，删除已经存在的指北针
            }
            IElementProperties pElePro = null;
            pElement = (IElement)pMapSurroundFrame;
            pElement.Geometry = (IGeometry)pEnv;
            pElePro = pElement as IElementProperties;
            pElePro.Name = "NorthArrows";
            pGraphicsContainer.AddElement(pElement, 0);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }
        #endregion

        #region  比例尺
        /// <summary>
        /// 比例尺
        /// </summary>
        /// <param name="pActiveView"></param>
        /// <param name="pPageLayout"></param>
        /// <param name="pEnv"></param>
        public void makeScaleBar(IActiveView pActiveView, IPageLayout pPageLayout, IEnvelope pEnv)
        {
            IMap pMap = pActiveView.FocusMap;
            IGraphicsContainer pGraphicsContainer = pPageLayout as IGraphicsContainer;
            IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;
            if (pStyleGalleryItem == null) return;
            IMapSurroundFrame pMapSurroundFrame = new MapSurroundFrameClass();
            pMapSurroundFrame.MapFrame = pMapFrame;
            pMapSurroundFrame.MapSurround = (IMapSurround)pStyleGalleryItem.Item;
            IElement pElement = PageLayoutControl_1.FindElementByName("ScaleBar");
            if (pElement != null)
            {
                pGraphicsContainer.DeleteElement(pElement);  //删除已经存在的比例尺
            }
            IElementProperties pElePro = null;
            pElement = (IElement)pMapSurroundFrame;
            pElement.Geometry = (IGeometry)pEnv;
            pElePro = pElement as IElementProperties;
            pElePro.Name = "ScaleBar";
            pGraphicsContainer.AddElement(pElement, 0);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }
        #endregion

        //添加删除网格
        private void AddGraticule_Click(object sender, EventArgs e)
        {
            try
            {
                IActiveView pActiveView = PageLayoutControl_1.ActiveView;
                IPageLayout pPageLayout = PageLayoutControl_1.PageLayout;
                DeleteMapGrid(pActiveView, pPageLayout);
                CreateGraticuleMapGrid(pActiveView, pPageLayout);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void CreateGraticuleMapGrid(IActiveView pActiveView, IPageLayout pPageLayout)
        {
            IMap pMap = pActiveView.FocusMap;
            IGraticule pGraticule = new GraticuleClass();//看这个改动是否争取
            pGraticule.Name = "Map Grid";
            //设置网格线的符号样式
            ICartographicLineSymbol pLineSymbol;
            pLineSymbol = new CartographicLineSymbolClass();
            pLineSymbol.Cap = esriLineCapStyle.esriLCSButt;
            pLineSymbol.Width = 1;
            pLineSymbol.Color = m_OperatePageLayout.GetRgbColor(166, 187, 208);
            pGraticule.LineSymbol = pLineSymbol;
            //设置网格的边框样式           
            ISimpleMapGridBorder simpleMapGridBorder = new SimpleMapGridBorderClass();
            ISimpleLineSymbol simpleLineSymbol = new SimpleLineSymbolClass();
            simpleLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
            simpleLineSymbol.Color = m_OperatePageLayout.GetRgbColor(100, 255, 0);
            simpleLineSymbol.Width = 2;
            simpleMapGridBorder.LineSymbol = simpleLineSymbol as ILineSymbol;
            pGraticule.Border = simpleMapGridBorder as IMapGridBorder;
            pGraticule.SetTickVisibility(true, true, true, true);
            //设置网格的主刻度的样式和可见性
            pGraticule.TickLength = 15;
            pLineSymbol = new CartographicLineSymbolClass();
            pLineSymbol.Cap = esriLineCapStyle.esriLCSButt;
            pLineSymbol.Width = 1;
            pLineSymbol.Color = m_OperatePageLayout.GetRgbColor(255, 187, 208);
            pGraticule.TickMarkSymbol = null;
            pGraticule.TickLineSymbol = pLineSymbol;
            pGraticule.SetTickVisibility(true, true, true, true);
            //设置网格的次级刻度的样式和可见性
            pGraticule.SubTickCount = 5;
            pGraticule.SubTickLength = 10;
            pLineSymbol = new CartographicLineSymbolClass();
            pLineSymbol.Cap = esriLineCapStyle.esriLCSButt;
            pLineSymbol.Width = 0.1;
            pLineSymbol.Color = m_OperatePageLayout.GetRgbColor(166, 187, 208);
            pGraticule.SubTickLineSymbol = pLineSymbol;
            pGraticule.SetSubTickVisibility(true, true, true, true);
            //设置网格的标签的样式和可见性
            IGridLabel pGridLabel;
            pGridLabel = pGraticule.LabelFormat;
            pGridLabel.LabelOffset = 15;
            stdole.StdFont pFont = new stdole.StdFont();
            pFont.Name = "Arial";
            pFont.Size = 16;
            pGraticule.LabelFormat.Font = pFont as stdole.IFontDisp;
            pGraticule.Visible = true;
            //创建IMeasuredGrid对象
            IMeasuredGrid pMeasuredGrid = new MeasuredGridClass();
            IProjectedGrid pProjectedGrid = pMeasuredGrid as IProjectedGrid;
            pProjectedGrid.SpatialReference = pMap.SpatialReference;
            pMeasuredGrid = pGraticule as IMeasuredGrid;
            //获取坐标范围，设置网格的起始点和间隔
            double MaxX, MaxY, MinX, MinY;
            pProjectedGrid.SpatialReference.GetDomain(out MinX, out MaxX, out MinY, out MaxY);
            pMeasuredGrid.FixedOrigin = true;
            pMeasuredGrid.Units = pMap.MapUnits;
            pMeasuredGrid.XIntervalSize = (MaxX - MinX) / 200;//纬度间隔
            pMeasuredGrid.XOrigin = MinX;
            pMeasuredGrid.YIntervalSize = (MaxY - MinY) / 200;//经度间隔.
            pMeasuredGrid.YOrigin = MinY;
            //将网格对象添加到地图控件中                              
            IGraphicsContainer pGraphicsContainer = pActiveView as IGraphicsContainer;
            IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;
            IMapGrids pMapGrids = pMapFrame as IMapGrids;
            pMapGrids.AddMapGrid(pGraticule);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null);
        }

        //measuregird网格
        private void AddMeasuredGrid_Click(object sender, EventArgs e)
        {
            IActiveView pActiveView = PageLayoutControl_1.ActiveView;
            IPageLayout pPageLayout = PageLayoutControl_1.PageLayout;
            DeleteMapGrid(pActiveView, pPageLayout);//删除已存在格网
            CreateMeasuredGrid(pActiveView, pPageLayout);
        }
        public void CreateMeasuredGrid(IActiveView pActiveView, IPageLayout pPageLayout)
        {
            IMap map = pActiveView.FocusMap;
            IMeasuredGrid pMeasuredGrid = new MeasuredGridClass();
            //设置格网基本属性           
            pMeasuredGrid.FixedOrigin = false;
            pMeasuredGrid.Units = map.MapUnits;
            pMeasuredGrid.XIntervalSize = 5;//纬度间隔           
            pMeasuredGrid.YIntervalSize = 5;//经度间隔.             
            //设置GridLabel格式
            IGridLabel pGridLabel = new FormattedGridLabelClass();
            IFormattedGridLabel pFormattedGridLabel = new FormattedGridLabelClass();
            INumericFormat pNumericFormat = new NumericFormatClass();
            pNumericFormat.AlignmentOption = esriNumericAlignmentEnum.esriAlignLeft;
            pNumericFormat.RoundingOption = esriRoundingOptionEnum.esriRoundNumberOfDecimals;
            pNumericFormat.RoundingValue = 0;
            pNumericFormat.ZeroPad = true;
            pFormattedGridLabel.Format = pNumericFormat as INumberFormat;
            pGridLabel = pFormattedGridLabel as IGridLabel;
            StdFont myFont = new stdole.StdFontClass();
            myFont.Name = "宋体";
            myFont.Size = 25;
            pGridLabel.Font = myFont as IFontDisp;
            IMapGrid pMapGrid = new MeasuredGridClass();
            pMapGrid = pMeasuredGrid as IMapGrid;
            pMapGrid.LabelFormat = pGridLabel;
            //将格网添加到地图上           
            IGraphicsContainer graphicsContainer = pPageLayout as IGraphicsContainer;
            IFrameElement frameElement = graphicsContainer.FindFrame(map);
            IMapFrame mapFrame = frameElement as IMapFrame;
            IMapGrids mapGrids = null;
            mapGrids = mapFrame as IMapGrids;
            mapGrids.AddMapGrid(pMapGrid);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null);
        }

        private void AddIndexGrid_Click(object sender, EventArgs e)
        {
            IActiveView pActiveView = PageLayoutControl_1.ActiveView;
            IPageLayout pPageLayout = PageLayoutControl_1.PageLayout;
            DeleteMapGrid(pActiveView, pPageLayout);
            CreateIndexGrid(pActiveView, pPageLayout);
        }
        public void CreateIndexGrid(IActiveView pActiveView, IPageLayout pPageLayout)
        {
            IIndexGrid pIndexGrid = new IndexGridClass();
            //设置Index属性
            pIndexGrid.ColumnCount = 5;
            pIndexGrid.RowCount = 5;
            String[] indexnum = { "A", "B", "C", "D", "E" };
            //设置IndexLabel
            int i = 0;
            for (i = 0; i <= (pIndexGrid.ColumnCount - 1); i++)
            {
                pIndexGrid.set_XLabel(i, indexnum[i]);
            }
            for (i = 0; i <= (pIndexGrid.RowCount - 1); i++)
            {
                pIndexGrid.set_YLabel(i, i.ToString());
            }
            //设置GridLabel格式
            IGridLabel pGridLabel = new RoundedTabStyleClass();
            StdFont myFont = new stdole.StdFontClass();
            myFont.Name = "宋体";
            myFont.Size = 18;
            pGridLabel.Font = myFont as IFontDisp;
            IMapGrid pmapGrid = new IndexGridClass();
            pmapGrid = pIndexGrid as IMapGrid;
            pmapGrid.LabelFormat = pGridLabel;
            //添加IndexGrid         
            IMapGrid pMapGrid = pIndexGrid;
            IMap pMap = pActiveView.FocusMap;
            IGraphicsContainer graphicsContainer = pPageLayout as IGraphicsContainer;
            IFrameElement frameElement = graphicsContainer.FindFrame(pMap);
            IMapFrame mapFrame = frameElement as IMapFrame;
            IMapGrids mapGrids = null;
            mapGrids = mapFrame as IMapGrids;
            mapGrids.AddMapGrid(pMapGrid);
            PageLayoutControl_1.Refresh();
        }
        #region 删除已存在格网
        public void DeleteMapGrid(IActiveView pActiveView, IPageLayout pPageLayout)
        {
            IMap pMap = pActiveView.FocusMap;
            IGraphicsContainer graphicsContainer = pPageLayout as IGraphicsContainer;
            IFrameElement frameElement = graphicsContainer.FindFrame(pMap);
            IMapFrame mapFrame = frameElement as IMapFrame;
            IMapGrids mapGrids = null;
            mapGrids = mapFrame as IMapGrids;
            if (mapGrids.MapGridCount > 0)
            {
                IMapGrid pMapGrid = mapGrids.get_MapGrid(0);
                mapGrids.DeleteMapGrid(pMapGrid);
            }
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null);
        }
        #endregion

        #endregion

        #region 单一符号化
        //单一符号化
        private void SingleSymbol_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmSimRender == null || frmSimRender.IsDisposed)
                {
                    frmSimRender = new frmSimpleRender();
                    frmSimRender.SimpleRender += new frmSimpleRender.SimpleRenderEventHandler(frmSimRender_SimpleRender);
                }
                frmSimRender.PMap = mainMapControl.Map;
                frmSimRender.InitUI();
                frmSimRender.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }
        void frmSimRender_SimpleRender(string sFeatClsName, IRgbColor pRgbColr)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            SimpleRenderer(pFeatLyr, pRgbColr);
        }
        /// <summary>
        /// 单一符号化
        /// </summary>
        /// <param name="pFeatLyr">渲染图层</param>
        /// <param name="pRgbColor">渲染颜色</param>
        private void SimpleRenderer(IFeatureLayer pFeatLyr, IRgbColor pRgbColor)
        {
            try
            {
                esriGeometryType types = pFeatLyr.FeatureClass.ShapeType;
                ISimpleRenderer pSimRender = new SimpleRendererClass();
                if (types == esriGeometryType.esriGeometryPolygon)
                {
                    ISimpleFillSymbol pSimFillSym = new SimpleFillSymbolClass();
                    pSimFillSym.Color = pRgbColor;
                    pSimRender.Symbol = pSimFillSym as ISymbol; // 设置渲染的样式 
                }
                else if (types == esriGeometryType.esriGeometryPoint)
                {
                    ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                    pSimpleMarkerSymbol.Color = pRgbColor;
                    pSimRender.Symbol = pSimpleMarkerSymbol as ISymbol;
                }
                else if (types == esriGeometryType.esriGeometryPolyline)
                {
                    ISimpleLineSymbol pSimpleLineSymbol = new SimpleLineSymbolClass();
                    pSimpleLineSymbol.Color = pRgbColor;
                    pSimRender.Symbol = pSimpleLineSymbol as ISymbol;
                }
                IGeoFeatureLayer pGeoFeatLyr = pFeatLyr as IGeoFeatureLayer;
                pGeoFeatLyr.Renderer = pSimRender as IFeatureRenderer;
                (mainMapControl.Map as IActiveView).PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                axTOCControl1.Update();
            }
            catch (Exception ex)
            {

            }
        }
        #endregion



        #region GP工具
        private void 缓冲区分析ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region 专题地图
        #region 唯一值符号化
        private void onlyValue_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmUniqueValueRen == null || frmUniqueValueRen.IsDisposed)
                {
                    frmUniqueValueRen = new frmUniqueValueRender();
                    frmUniqueValueRen.UniqueValueRender += new frmUniqueValueRender.UniqueValueRenderEventHandler(frmUniqueValueRen_UniqueValueRender);
                }
                frmUniqueValueRen.Map = mainMapControl.Map;
                frmUniqueValueRen.InitUI();
                frmUniqueValueRen.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }
        void frmUniqueValueRen_UniqueValueRender(string sFeatClsName, string sFieldName)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            UniqueValueRenderer(pFeatLyr, sFieldName);

        }
        /// <summary>
        /// 唯一值符号化
        /// </summary>
        /// <param name="pFeatLyr">渲染图层</param>
        /// <param name="sFieldName">渲染字段</param>
        private void UniqueValueRenderer(IFeatureLayer pFeatLyr, string sFieldName)
        {
            try
            {
                IGeoFeatureLayer pGeoFeatLyr = pFeatLyr as IGeoFeatureLayer;
                ITable pTable = pFeatLyr as ITable;
                IUniqueValueRenderer pUniqueValueRender = new UniqueValueRendererClass();

                int intFieldNumber = pTable.FindField(sFieldName);
                pUniqueValueRender.FieldCount = 1;//设置唯一值符号化的关键字段为一个
                pUniqueValueRender.set_Field(0, sFieldName);//设置唯一值符号化的第一个关键字段

                IRandomColorRamp pRandColorRamp = new RandomColorRampClass();
                pRandColorRamp.StartHue = 0;
                pRandColorRamp.MinValue = 0;
                pRandColorRamp.MinSaturation = 15;
                pRandColorRamp.EndHue = 360;
                pRandColorRamp.MaxValue = 100;
                pRandColorRamp.MaxSaturation = 30;
                //根据渲染字段的值的个数，设置一组随机颜色，如某一字段有5个值，则创建5个随机颜色与之匹配
                IQueryFilter pQueryFilter = new QueryFilterClass();
                pRandColorRamp.Size = pFeatLyr.FeatureClass.FeatureCount(pQueryFilter);
                bool bSuccess = false;
                pRandColorRamp.CreateRamp(out bSuccess);

                IEnumColors pEnumRamp = pRandColorRamp.Colors;
                IColor pNextUniqueColor = null;
                //查询字段的值
                pQueryFilter = new QueryFilterClass();
                pQueryFilter.AddField(sFieldName);
                ICursor pCursor = pTable.Search(pQueryFilter, true);
                IRow pNextRow = pCursor.NextRow();
                object codeValue = null;
                IRowBuffer pNextRowBuffer = null;


                while (pNextRow != null)
                {
                    pNextRowBuffer = pNextRow as IRowBuffer;
                    codeValue = pNextRowBuffer.get_Value(intFieldNumber);//获取渲染字段的每一个值

                    pNextUniqueColor = pEnumRamp.Next();
                    if (pNextUniqueColor == null)
                    {
                        pEnumRamp.Reset();
                        pNextUniqueColor = pEnumRamp.Next();
                    }
                    IFillSymbol pFillSymbol = null;
                    ILineSymbol pLineSymbol;
                    IMarkerSymbol pMarkerSymbol;
                    switch (pGeoFeatLyr.FeatureClass.ShapeType)
                    {
                        case esriGeometryType.esriGeometryPolygon:
                            {
                                pFillSymbol = new SimpleFillSymbolClass();
                                pFillSymbol.Color = pNextUniqueColor;
                                pUniqueValueRender.AddValue(codeValue.ToString(), "", pFillSymbol as ISymbol);//添加渲染字段的值和渲染样式
                                pNextRow = pCursor.NextRow();
                                break;
                            }
                        case esriGeometryType.esriGeometryPolyline:
                            {
                                pLineSymbol = new SimpleLineSymbolClass();
                                pLineSymbol.Color = pNextUniqueColor;
                                pUniqueValueRender.AddValue(codeValue.ToString(), "", pLineSymbol as ISymbol);//添加渲染字段的值和渲染样式
                                pNextRow = pCursor.NextRow();
                                break;
                            }
                        case esriGeometryType.esriGeometryPoint:
                            {
                                pMarkerSymbol = new SimpleMarkerSymbolClass();
                                pMarkerSymbol.Color = pNextUniqueColor;
                                pUniqueValueRender.AddValue(codeValue.ToString(), "", pMarkerSymbol as ISymbol);//添加渲染字段的值和渲染样式
                                pNextRow = pCursor.NextRow();
                                break;
                            }
                    }
                }
                pGeoFeatLyr.Renderer = pUniqueValueRender as IFeatureRenderer;
                mainMapControl.Refresh();
                axTOCControl1.Update();
            }
            catch (Exception ex)
            {

            }

        }
        #endregion

        #region 唯一值多字段



        private void manyZIduan_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmUniqueValueMany_fields == null || frmUniqueValueMany_fields.IsDisposed)
                {
                    frmUniqueValueMany_fields = new frmUniqueValueMany_fields();
                    frmUniqueValueMany_fields.UniqueValueRender += new frmUniqueValueMany_fields.UniqueValueRenderEventHandler(frmUniqueValueMany_fields_UniqueValueRender);
                }

                frmUniqueValueMany_fields.Map = mainMapControl.Map;
                frmUniqueValueMany_fields.InitUI();
                frmUniqueValueMany_fields.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }
        void frmUniqueValueMany_fields_UniqueValueRender(string sFeatClsName, string[] sFieldName)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            UniqueValueMany_fieldsRenderer(pFeatLyr, sFieldName);
        }
        /// <summary>
        /// 唯一值多字段
        /// </summary>
        /// <param name="pFeatLyr">渲染图层</param>
        /// <param name="sFieldName">渲染字段</param>
        private void UniqueValueMany_fieldsRenderer(IFeatureLayer pFeatLyr, string[] sFieldName)
        {
            IUniqueValueRenderer pUniqueValueRender;
            IColor pNextUniqueColor;
            IEnumColors pEnumRamp;
            ITable pTable;
            IRow pNextRow;
            ICursor pCursor;
            IQueryFilter pQueryFilter;
            IRandomColorRamp pRandColorRamp = new RandomColorRampClass();
            pRandColorRamp.StartHue = 0;
            pRandColorRamp.MinValue = 0;
            pRandColorRamp.MinSaturation = 15;
            pRandColorRamp.EndHue = 360;
            pRandColorRamp.MaxValue = 100;
            pRandColorRamp.MaxSaturation = 30;
            //根据渲染字段值的个数，设置一组随即颜色，如某一字段有5个不同值，则创建5个随机颜色与之匹配
            IQueryFilter pQueryFilter1 = new QueryFilterClass();
            pRandColorRamp.Size = pFeatLyr.FeatureClass.FeatureCount(pQueryFilter1);
            bool bSuccess = false;
            pRandColorRamp.CreateRamp(out bSuccess);
            //所选字段数为两个时
            if (sFieldName.Length == 2)
            {
                string sFieldName1 = sFieldName[0];
                string sFieldName2 = sFieldName[1];
                IGeoFeatureLayer pGeoFeatureL = (IGeoFeatureLayer)pFeatLyr;
                pUniqueValueRender = new UniqueValueRendererClass();
                pTable = (ITable)pGeoFeatureL;
                int pFieldNumber = pTable.FindField(sFieldName1);
                int pFieldNumber2 = pTable.FindField(sFieldName2);
                pUniqueValueRender.FieldCount = 2;//设置渲染字段的个数
                pUniqueValueRender.set_Field(0, sFieldName1);//设置渲染的第一个字段
                pUniqueValueRender.set_Field(1, sFieldName2);//设置渲染的第二个字段
                pEnumRamp = pRandColorRamp.Colors;
                pNextUniqueColor = null;
                //获取渲染字段的每个属性值
                pQueryFilter = new QueryFilterClass();
                pQueryFilter.AddField(sFieldName1);
                pQueryFilter.AddField(sFieldName2);
                pCursor = pTable.Search(pQueryFilter, true);
                pNextRow = pCursor.NextRow();
                string codeValue;//这里的codeValue还可以定义成object类型
                while (pNextRow != null)
                {
                    codeValue = pNextRow.get_Value(pFieldNumber).ToString() + pUniqueValueRender.FieldDelimiter + pNextRow.get_Value(pFieldNumber2).ToString();
                    pNextUniqueColor = pEnumRamp.Next();
                    if (pNextUniqueColor == null)
                    {
                        pEnumRamp.Reset();
                        pNextUniqueColor = pEnumRamp.Next();
                    }
                    IFillSymbol pFillSymbol;
                    ILineSymbol pLineSymbol;
                    IMarkerSymbol pMarkerSymbol;
                    switch (pGeoFeatureL.FeatureClass.ShapeType)
                    {
                        case esriGeometryType.esriGeometryPolygon:
                            {
                                pFillSymbol = new SimpleFillSymbolClass();
                                pFillSymbol.Color = pNextUniqueColor;
                                //设置渲染字段组合值对应的符号
                                pUniqueValueRender.AddValue(codeValue, sFieldName1 + " " + sFieldName2, (ISymbol)pFillSymbol);
                                break;
                            }
                        case esriGeometryType.esriGeometryPolyline:
                            {
                                pLineSymbol = new SimpleLineSymbolClass();
                                pLineSymbol.Color = pNextUniqueColor;
                                //设置渲染字段组合值对应的符号
                                pUniqueValueRender.AddValue(codeValue, sFieldName1 + " " + sFieldName2, (ISymbol)pLineSymbol);
                                break;
                            }
                        case esriGeometryType.esriGeometryPoint:
                            {
                                pMarkerSymbol = new SimpleMarkerSymbolClass();
                                pMarkerSymbol.Color = pNextUniqueColor;
                                //设置渲染字段组合值对应的符号
                                pUniqueValueRender.AddValue(codeValue, sFieldName1 + " " + sFieldName2, (ISymbol)pMarkerSymbol);
                                break;
                            }
                    }
                    pNextRow = pCursor.NextRow();
                }
                pGeoFeatureL.Renderer = (IFeatureRenderer)pUniqueValueRender;
                mainMapControl.Refresh();
                axTOCControl1.Update();
            }
            else if (sFieldName.Length == 3)
            {
                string sFieldName1 = sFieldName[0];
                string sFieldName2 = sFieldName[1];
                string sFieldName3 = sFieldName[2];
                IGeoFeatureLayer pGeoFeatureL = (IGeoFeatureLayer)pFeatLyr;
                pUniqueValueRender = new UniqueValueRendererClass();
                pTable = (ITable)pGeoFeatureL;
                int pFieldNumber = pTable.FindField(sFieldName1);
                int pFieldNumber2 = pTable.FindField(sFieldName2);
                int pFieldNumber3 = pTable.FindField(sFieldName3);
                pUniqueValueRender.FieldCount = 3;
                pUniqueValueRender.set_Field(0, sFieldName1);
                pUniqueValueRender.set_Field(1, sFieldName2);
                pUniqueValueRender.set_Field(2, sFieldName3);
                pEnumRamp = pRandColorRamp.Colors;
                pNextUniqueColor = null;
                pQueryFilter = new QueryFilterClass();
                pQueryFilter.AddField(sFieldName1);
                pQueryFilter.AddField(sFieldName2);
                pQueryFilter.AddField(sFieldName3);
                pCursor = pTable.Search(pQueryFilter, true);
                pNextRow = pCursor.NextRow();
                string codeValue;
                while (pNextRow != null)
                {
                    codeValue = pNextRow.get_Value(pFieldNumber).ToString() + pUniqueValueRender.FieldDelimiter + pNextRow.get_Value(pFieldNumber2).ToString() + pUniqueValueRender.FieldDelimiter + pNextRow.get_Value(pFieldNumber3).ToString();
                    pNextUniqueColor = pEnumRamp.Next();
                    if (pNextUniqueColor == null)
                    {
                        pEnumRamp.Reset();
                        pNextUniqueColor = pEnumRamp.Next();
                    }
                    IFillSymbol pFillSymbol;
                    ILineSymbol pLineSymbol;
                    IMarkerSymbol pMarkerSymbol;
                    switch (pGeoFeatureL.FeatureClass.ShapeType)
                    {
                        case esriGeometryType.esriGeometryPolygon:
                            {
                                pFillSymbol = new SimpleFillSymbolClass();
                                pFillSymbol.Color = pNextUniqueColor;
                                pUniqueValueRender.AddValue(codeValue, sFieldName1 + " " + sFieldName2 + "" + sFieldName3, (ISymbol)pFillSymbol);
                                break;
                            }
                        case esriGeometryType.esriGeometryPolyline:
                            {
                                pLineSymbol = new SimpleLineSymbolClass();
                                pLineSymbol.Color = pNextUniqueColor;
                                pUniqueValueRender.AddValue(codeValue, sFieldName1 + " " + sFieldName2 + "" + sFieldName3, (ISymbol)pLineSymbol);
                                break;
                            }
                        case esriGeometryType.esriGeometryPoint:
                            {
                                pMarkerSymbol = new SimpleMarkerSymbolClass();
                                pMarkerSymbol.Color = pNextUniqueColor;
                                pUniqueValueRender.AddValue(codeValue, sFieldName1 + " " + sFieldName2 + "" + sFieldName3, (ISymbol)pMarkerSymbol);
                                break;
                            }
                    }
                    pNextRow = pCursor.NextRow();
                }
                pGeoFeatureL.Renderer = (IFeatureRenderer)pUniqueValueRender;
                mainMapControl.Refresh();
                axTOCControl1.Update();
            }
            




        }
        #endregion
        private void 分级符号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmGraduatedSymbols == null || frmGraduatedSymbols.IsDisposed)
                {
                    frmGraduatedSymbols = new frmGraduatedSymbols();
                    frmGraduatedSymbols.GraduatedSymbols += new frmGraduatedSymbols.GraduatedSymbolsEventHandler(frmGraduatedSymbols_GraduatedSymbols);
                }
                frmGraduatedSymbols.Map = mainMapControl.Map;
                frmGraduatedSymbols.InitUI();
                frmGraduatedSymbols.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }
        // 分级符号 
        void frmGraduatedSymbols_GraduatedSymbols(string sFeatClsName, string sFieldName, int numclasses)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            GraduatedSymbols(pFeatLyr, sFieldName, numclasses);
        }
        /// <summary>
        /// 分级符号
        /// </summary>
        /// <param name="pFeatLyr">渲染图层</param>
        /// <param name="sFieldName">渲染字段</param>
        /// <param name="numclasses">分级数目</param>
        public void GraduatedSymbols(IFeatureLayer pFeatLyr, string sFieldName, int numclasses)
        {
            ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
            pSimpleMarkerSymbol.Color = m_OperateMap.GetRgbColor(255, 100, 100);
            ISimpleLineSymbol pSimpleLineSymbol = new SimpleLineSymbolClass();
            pSimpleLineSymbol.Color = m_OperateMap.GetRgbColor(255, 100, 100);
            int IbreakIndex;
            object dataFrequency;
            object dataValues;

            //获得要着色的图层
            IGeoFeatureLayer pGeoFeatureL = pFeatLyr as IGeoFeatureLayer;
            ITable pTable = pGeoFeatureL.FeatureClass as ITable;
            ITableHistogram pTableHistogram = new BasicTableHistogramClass();
            IBasicHistogram pBasicHistogram = (IBasicHistogram)pTableHistogram;
            pTableHistogram.Field = sFieldName;
            pTableHistogram.Table = pTable;
            pBasicHistogram.GetHistogram(out dataValues, out dataFrequency);//获取渲染字段的值及其出现的频率                    
            IClassifyGEN pClassify = new EqualIntervalClass();
            try
            {
                pClassify.Classify(dataValues, dataFrequency, ref numclasses);//根据获取字段的值和出现的频率对其进行等级划分 
            }
            catch (Exception ex)
            {
            }
            //返回一个数组
            double[] Classes = (double[])pClassify.ClassBreaks;
            int ClassesCount = Classes.GetUpperBound(0);
            IClassBreaksRenderer pClassBreakRenderer = new ClassBreaksRendererClass();
            pClassBreakRenderer.Field = sFieldName;// 设置分级字段
            //设置着色对象的分级数目
            pClassBreakRenderer.BreakCount = ClassesCount;//设置分级数目
            pClassBreakRenderer.SortClassesAscending = true;//升序排列
            //需要注意的是分级着色对象中的symbol和break的下标都是从0开始
            double symbolSizeOrigin = 5.0;
            if (ClassesCount <= 5)
            {
                symbolSizeOrigin = 8;
            }
            if (ClassesCount < 10 && ClassesCount > 5)
            {
                symbolSizeOrigin = 7;
            }
            IFillSymbol pBackgroundSymbol = new SimpleFillSymbolClass();
            pBackgroundSymbol.Color = m_OperateMap.GetRgbColor(255, 255, 100);
            //不同的要素类型，生成不同的分级符号
            switch (pGeoFeatureL.FeatureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryPolygon:
                    {
                        for (IbreakIndex = 0; IbreakIndex <= ClassesCount - 1; IbreakIndex++)
                        {
                            pClassBreakRenderer.set_Break(IbreakIndex, Classes[IbreakIndex + 1]);
                            pClassBreakRenderer.BackgroundSymbol = pBackgroundSymbol;
                            pSimpleMarkerSymbol.Size = symbolSizeOrigin + IbreakIndex * symbolSizeOrigin / 3.0d;
                            pClassBreakRenderer.set_Symbol(IbreakIndex, (ISymbol)pSimpleMarkerSymbol);
                        }
                        break;
                    }
                case esriGeometryType.esriGeometryPolyline:
                    {
                        for (IbreakIndex = 0; IbreakIndex <= ClassesCount - 1; IbreakIndex++)
                        {
                            pClassBreakRenderer.set_Break(IbreakIndex, Classes[IbreakIndex + 1]);
                            pSimpleLineSymbol.Width = symbolSizeOrigin / 5 + IbreakIndex * (symbolSizeOrigin / 5) / 5.0d;
                            pClassBreakRenderer.set_Symbol(IbreakIndex, (ISymbol)pSimpleLineSymbol);
                        }
                        break;
                    }
                case esriGeometryType.esriGeometryPoint:
                    {
                        for (IbreakIndex = 0; IbreakIndex <= ClassesCount - 1; IbreakIndex++)
                        {
                            pClassBreakRenderer.set_Break(IbreakIndex, Classes[IbreakIndex + 1]);
                            pSimpleMarkerSymbol.Size = symbolSizeOrigin + IbreakIndex * symbolSizeOrigin / 3.0d;
                            pClassBreakRenderer.set_Symbol(IbreakIndex, (ISymbol)pSimpleMarkerSymbol);
                        }
                        break;
                    }
            }
            pGeoFeatureL.Renderer = pClassBreakRenderer as IFeatureRenderer;
            mainMapControl.ActiveView.Refresh();
            axTOCControl1.Update();
        }

        private void 比例符号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmProportional == null || frmProportional.IsDisposed)
                {
                    frmProportional = new frmProportional();
                    frmProportional.Proportional += new frmProportional.ProportionalEventHandler(frmProportional_Proportional);
                }
                frmProportional.Map = mainMapControl.Map;
                frmProportional.InitUI();
                frmProportional.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }
        // 比例符号 
        void frmProportional_Proportional(string sFeatClsName, string sFieldName)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            Proportional(pFeatLyr, sFieldName);
        }
        /// <summary>
        /// 比例符号化
        /// </summary>
        /// <param name="sender">渲染图层</param>
        /// <param name="e">渲染字段</param>        
        private void Proportional(IFeatureLayer pFeatLyr, string sFieldName)
        {
            try
            {
                IGeoFeatureLayer pGeoFeatureLayer = pFeatLyr as IGeoFeatureLayer;
                ITable pTable = pFeatLyr as ITable;
                ICursor pCursor = pTable.Search(null, true);
                //利用IDataStatistics和IStatisticsResults获取渲染字段的统计值，最主要是或得最大值和最小值
                IDataStatistics pDataStatistics = new DataStatisticsClass();
                pDataStatistics.Cursor = pCursor;
                pDataStatistics.Field = sFieldName;
                IStatisticsResults pStatisticsResult = pDataStatistics.Statistics;
                if (pStatisticsResult != null)
                {
                    //设置渲染背景色
                    IFillSymbol pFillSymbol = new SimpleFillSymbolClass();
                    pFillSymbol.Color = m_OperateMap.GetRgbColor(155, 255, 0);
                    //设置比例符号的样式                 
                    ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                    pSimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSDiamond;
                    pSimpleMarkerSymbol.Size = 3;
                    pSimpleMarkerSymbol.Color = m_OperateMap.GetRgbColor(255, 90, 0);
                    IProportionalSymbolRenderer pProportionalSymbolRenderer = new ProportionalSymbolRendererClass();
                    pProportionalSymbolRenderer.ValueUnit = esriUnits.esriUnknownUnits;//设置渲染单位
                    pProportionalSymbolRenderer.Field = sFieldName; //设置渲染字段   
                    pProportionalSymbolRenderer.FlanneryCompensation = false;//是否使用Flannery补偿
                    pProportionalSymbolRenderer.MinDataValue = pStatisticsResult.Minimum;//获取渲染字段的最大值
                    pProportionalSymbolRenderer.MaxDataValue = pStatisticsResult.Maximum;//获取渲染字段的最小值
                    pProportionalSymbolRenderer.BackgroundSymbol = pFillSymbol;
                    pProportionalSymbolRenderer.MinSymbol = pSimpleMarkerSymbol as ISymbol;//向设置渲染字段最小值的渲染符号，其余值的符号根据此符号产生
                    pProportionalSymbolRenderer.LegendSymbolCount = 5;// 设置TOC控件中显示的数目
                    pProportionalSymbolRenderer.CreateLegendSymbols();//生成图例
                    pGeoFeatureLayer.Renderer = pProportionalSymbolRenderer as IFeatureRenderer;
                }
                mainMapControl.Refresh();
                axTOCControl1.Update();
            }
            catch (Exception ex)
            {
            }
        }

        private void 点密度ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmDotDensity == null || frmDotDensity.IsDisposed)
                {
                    frmDotDensity = new frmDotDensity();
                    frmDotDensity.DotDensity += new frmDotDensity.DotDensityEventHandler(frmDotDensity_DotDensity);
                }
                frmDotDensity.Map = mainMapControl.Map;
                frmDotDensity.InitUI();
                frmDotDensity.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }
        // 点密度
        void frmDotDensity_DotDensity(string sFeatClsName, string sFieldName, int intRendererDensity)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            DotDensity(pFeatLyr, sFieldName, intRendererDensity);
        }
        /// <summary>
        /// 点密度图
        /// </summary>
        /// <param name="pFeatLyr">渲染图层</param>
        /// <param name="sFieldName">渲染字段</param>
        /// <param name="intRendererDensity">每个点多代表的值</param>           
        private void DotDensity(IFeatureLayer pFeatLyr, string sFieldName, int intRendererDensity)
        {
            try
            {
                IGeoFeatureLayer pGeoFeatureLayer = pFeatLyr as IGeoFeatureLayer;
                IDotDensityRenderer pDotDensityRenderer = new DotDensityRendererClass();
                IRendererFields pRendererFields = pDotDensityRenderer as IRendererFields;
                //设置渲染字段               
                pRendererFields.AddField(sFieldName);
                //设置填充背景色
                IDotDensityFillSymbol pDotDensityFillSymbol = new DotDensityFillSymbolClass();
                pDotDensityFillSymbol.DotSize = 3;
                pDotDensityFillSymbol.BackgroundColor = m_OperateMap.GetRgbColor(0, 255, 0);
                //设置渲染符号
                ISymbolArray pSymbolArray = pDotDensityFillSymbol as ISymbolArray;
                ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                pSimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                pSimpleMarkerSymbol.Color = m_OperateMap.GetRgbColor(0, 0, 255);
                pSymbolArray.AddSymbol(pSimpleMarkerSymbol as ISymbol);
                pDotDensityRenderer.DotDensitySymbol = pDotDensityFillSymbol;
                //设置渲染密度，即每个点符号所代表的数值大小
                pDotDensityRenderer.DotValue = intRendererDensity;
                //创建图例
                pDotDensityRenderer.CreateLegend();
                pGeoFeatureLayer.Renderer = pDotDensityRenderer as IFeatureRenderer;
                mainMapControl.Refresh();
                axTOCControl1.Update();
            }
            catch (Exception ex)
            {

            }
        }

        private void Twovalue_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmScaleDependentRenderer == null || frmScaleDependentRenderer.IsDisposed)
                {
                    frmBivariateRenderer = new frmBivariateRenderer();
                    frmBivariateRenderer.BivariateRenderer += new frmBivariateRenderer.BivariateRendererEventHandler(frmBivariateRenderer_BivariateRenderer);
                }
                frmBivariateRenderer.Map = mainMapControl.Map;
                frmBivariateRenderer.InitUI();
                frmBivariateRenderer.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }
        void frmBivariateRenderer_BivariateRenderer(string sFeatClsName, string sFieldName, int numclasses)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            BivariateRenderer(pFeatLyr, sFieldName, numclasses);
        }
        private void BivariateRenderer(IFeatureLayer pFeatLyr, string sFieldName, int numclasses)
        {
            IGeoFeatureLayer pGeoFeatLyr = pFeatLyr as IGeoFeatureLayer;
            ITable pTable = pFeatLyr as ITable;
            IUniqueValueRenderer pUniqueValueRender = new UniqueValueRendererClass();
            int intFieldNumber = pTable.FindField(sFieldName);
            pUniqueValueRender.FieldCount = 1;          //设置唯一值符号化的关键字段为一个
            pUniqueValueRender.set_Field(0, sFieldName);//设置唯一值符号化的第一个关键字段

            IRandomColorRamp pRandColorRamp = new RandomColorRampClass();
            pRandColorRamp.StartHue = 0;
            pRandColorRamp.MinValue = 0;
            pRandColorRamp.MinSaturation = 15;
            pRandColorRamp.EndHue = 360;
            pRandColorRamp.MaxValue = 100;
            pRandColorRamp.MaxSaturation = 30;
            //根据渲染字段的值的个数，设置一组随机颜色，如某一字段有5个值，则创建5个随机颜色与之匹配
            IQueryFilter pQueryFilter = new QueryFilterClass();
            pRandColorRamp.Size = pFeatLyr.FeatureClass.FeatureCount(pQueryFilter);
            bool bSuccess = false;
            pRandColorRamp.CreateRamp(out bSuccess);
            IEnumColors pEnumRamp = pRandColorRamp.Colors;
            IColor pNextUniqueColor = null;
            pQueryFilter = new QueryFilterClass();
            pQueryFilter.AddField(sFieldName);
            ICursor pCursor = pTable.Search(pQueryFilter, true);
            IRow pNextRow = pCursor.NextRow();
            object codeValue = null;
            IRowBuffer pNextRowBuffer = null;


            while (pNextRow != null)
            {
                pNextRowBuffer = pNextRow as IRowBuffer;
                codeValue = pNextRowBuffer.get_Value(intFieldNumber);//获取渲染字段的每一个值

                pNextUniqueColor = pEnumRamp.Next();
                if (pNextUniqueColor == null)
                {
                    pEnumRamp.Reset();
                    pNextUniqueColor = pEnumRamp.Next();
                }
                IFillSymbol pFillSymbol = null;
                ILineSymbol pLineSymbol;
                IMarkerSymbol pMarkerSymbol;
                switch (pGeoFeatLyr.FeatureClass.ShapeType)
                {
                    case esriGeometryType.esriGeometryPolygon:
                        {
                            pFillSymbol = new SimpleFillSymbolClass();
                            pFillSymbol.Color = pNextUniqueColor;
                            pUniqueValueRender.AddValue(codeValue.ToString(), "", pFillSymbol as ISymbol);//添加渲染字段的值和渲染样式
                            pNextRow = pCursor.NextRow();
                            break;
                        }
                    case esriGeometryType.esriGeometryPolyline:
                        {
                            pLineSymbol = new SimpleLineSymbolClass();
                            pLineSymbol.Color = pNextUniqueColor;
                            pUniqueValueRender.AddValue(codeValue.ToString(), "", pLineSymbol as ISymbol);//添加渲染字段的值和渲染样式
                            pNextRow = pCursor.NextRow();
                            break;
                        }
                    case esriGeometryType.esriGeometryPoint:
                        {
                            pMarkerSymbol = new SimpleMarkerSymbolClass();
                            pMarkerSymbol.Color = pNextUniqueColor;
                            pUniqueValueRender.AddValue(codeValue.ToString(), "", pMarkerSymbol as ISymbol);//添加渲染字段的值和渲染样式
                            pNextRow = pCursor.NextRow();
                            break;
                        }
                }

                // 分级渲染  
                ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                int IbreakIndex;
                object dataFrequency;
                object dataValues;
                //获得要着色的图层             
                ITable pTable2 = pGeoFeatLyr.FeatureClass as ITable;
                ITableHistogram pTableHistogram = new BasicTableHistogramClass();
                IBasicHistogram pBasicHistogram = (IBasicHistogram)pTableHistogram;
                pTableHistogram.Field = sFieldName;
                pTableHistogram.Table = pTable2;
                pBasicHistogram.GetHistogram(out dataValues, out dataFrequency);//获取渲染字段的值及其出现的频率
                //分级方法，用于根据获得的值计算得出符合要求的数据           
                IClassifyGEN pClassify = new EqualIntervalClass();
                try
                {
                    pClassify.Classify(dataValues, dataFrequency, ref numclasses);//根据获取字段的值和出现的频率对其进行等级划分 
                }
                catch (Exception ex)
                {
                }
                //返回一个数组
                double[] Classes = (double[])pClassify.ClassBreaks;
                int ClassesCount = Classes.GetUpperBound(0);

                ILegendInfo pLegendInfo = new ClassBreaksRendererClass();
                pLegendInfo.SymbolsAreGraduated = true;

                IClassBreaksRenderer pClassBreakRenderer = pLegendInfo as IClassBreaksRenderer;
                pClassBreakRenderer.Field = sFieldName;// 设置分级字段

                //设置着色对象的分级数目
                pClassBreakRenderer.BreakCount = ClassesCount;//设置分级数目   自己改的
                pClassBreakRenderer.SortClassesAscending = true;//升序排列
                //需要注意的是分级着色对象中的symbol和break的下标都是从0开始
                double symbolSizeOrigin = 5.0;
                if (ClassesCount <= 5)
                {
                    symbolSizeOrigin = 12;
                }
                if (ClassesCount < 10 && ClassesCount > 5)
                {
                    symbolSizeOrigin = 7;
                }
                IFillSymbol pBackgroundSymbol = new SimpleFillSymbolClass();
                for (IbreakIndex = 0; IbreakIndex <= ClassesCount - 1; IbreakIndex++)
                {
                    pClassBreakRenderer.set_Break(IbreakIndex, Classes[IbreakIndex + 1]);
                    pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                    pSimpleMarkerSymbol.Color = m_OperateMap.GetRgbColor(255, 100, 100);
                    //当渲染面图层时，需要设置BackgroundSymbol
                    switch (pFeatLyr.FeatureClass.ShapeType)
                    {
                        case esriGeometryType.esriGeometryPolygon:
                            {
                                pClassBreakRenderer.BackgroundSymbol = pBackgroundSymbol;
                                break;
                            }
                    }

                    pSimpleMarkerSymbol.Size = symbolSizeOrigin + IbreakIndex * symbolSizeOrigin / 3.0d;
                    pClassBreakRenderer.set_Symbol(IbreakIndex, (ISymbol)pSimpleMarkerSymbol);
                }

                IBivariateRenderer bivariateRenderer = new BiUniqueValueRendererClass();
                bivariateRenderer.MainRenderer = (IFeatureRenderer)pUniqueValueRender;//设置主渲染
                bivariateRenderer.VariationRenderer = (IFeatureRenderer)pClassBreakRenderer;//设置二元渲染
                bivariateRenderer.CreateLegend();
                pGeoFeatLyr.Renderer = (IFeatureRenderer)bivariateRenderer;
                mainMapControl.ActiveView.Refresh();
                axTOCControl1.Update();
            }
        }

        private void manymany_Click(object sender, EventArgs e)
        {
            try
            {
                if (frmScaleDependentRenderer == null || frmScaleDependentRenderer.IsDisposed)
                {
                    frmScaleDependentRenderer = new frmScaleDependentRenderer();
                    frmScaleDependentRenderer.ScaleDependentRenderer += new frmScaleDependentRenderer.ScaleDependentRendererEventHandler(frmScaleDependentRenderer_ScaleDependentRenderer);
                }
                frmScaleDependentRenderer.Map = mainMapControl.Map;
                frmScaleDependentRenderer.InitUI();
                frmScaleDependentRenderer.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }
        void frmScaleDependentRenderer_ScaleDependentRenderer(string sFeatClsName, string sFieldName, int numclasses)
        {
            IFeatureLayer pFeatLyr = m_OperateMap.GetFeatLyrByName(mainMapControl.Map, sFeatClsName);
            ScaleDependentRenderer(pFeatLyr, sFieldName, numclasses);
        }
        private void ScaleDependentRenderer(IFeatureLayer pFeatLyr, string sFieldName, int numclasses)
        {
            IGeoFeatureLayer pGeoFeatLyr = pFeatLyr as IGeoFeatureLayer;
            ITable pTable = pFeatLyr as ITable;
            //唯一值渲染
            IUniqueValueRenderer pUniqueValueRender = new UniqueValueRendererClass();
            int intFieldNumber = pTable.FindField(sFieldName);
            pUniqueValueRender.FieldCount = 1;          //设置唯一值符号化的关键字段为一个
            pUniqueValueRender.set_Field(0, sFieldName);//设置唯一值符号化的第一个关键字段

            IRandomColorRamp pRandColorRamp = new RandomColorRampClass();
            pRandColorRamp.StartHue = 0;
            pRandColorRamp.MinValue = 0;
            pRandColorRamp.MinSaturation = 15;
            pRandColorRamp.EndHue = 360;
            pRandColorRamp.MaxValue = 100;
            pRandColorRamp.MaxSaturation = 30;
            //根据渲染字段的值的个数，设置一组随机颜色，如某一字段有5个值，则创建5个随机颜色与之匹配
            IQueryFilter pQueryFilter = new QueryFilterClass();
            pRandColorRamp.Size = pFeatLyr.FeatureClass.FeatureCount(pQueryFilter);
            bool bSuccess = false;
            pRandColorRamp.CreateRamp(out bSuccess);

            IEnumColors pEnumRamp = pRandColorRamp.Colors;
            IColor pNextUniqueColor = null;

            pQueryFilter = new QueryFilterClass();
            pQueryFilter.AddField(sFieldName);
            ICursor pCursor = pTable.Search(pQueryFilter, true);
            IRow pNextRow = pCursor.NextRow();
            object codeValue = null;
            IRowBuffer pNextRowBuffer = null;


            while (pNextRow != null)
            {
                pNextRowBuffer = pNextRow as IRowBuffer;
                codeValue = pNextRowBuffer.get_Value(intFieldNumber);//获取渲染字段的每一个值

                pNextUniqueColor = pEnumRamp.Next();
                if (pNextUniqueColor == null)
                {
                    pEnumRamp.Reset();
                    pNextUniqueColor = pEnumRamp.Next();
                }
                IFillSymbol pFillSymbol = null;
                ILineSymbol pLineSymbol;
                IMarkerSymbol pMarkerSymbol;
                switch (pGeoFeatLyr.FeatureClass.ShapeType)
                {
                    case esriGeometryType.esriGeometryPolygon:
                        {
                            pFillSymbol = new SimpleFillSymbolClass();
                            pFillSymbol.Color = pNextUniqueColor;
                            pUniqueValueRender.AddValue(codeValue.ToString(), "", pFillSymbol as ISymbol);//添加渲染字段的值和渲染样式
                            pNextRow = pCursor.NextRow();
                            break;
                        }
                    case esriGeometryType.esriGeometryPolyline:
                        {
                            pLineSymbol = new SimpleLineSymbolClass();
                            pLineSymbol.Color = pNextUniqueColor;
                            pUniqueValueRender.AddValue(codeValue.ToString(), "", pLineSymbol as ISymbol);//添加渲染字段的值和渲染样式
                            pNextRow = pCursor.NextRow();
                            break;
                        }
                    case esriGeometryType.esriGeometryPoint:
                        {
                            pMarkerSymbol = new SimpleMarkerSymbolClass();
                            pMarkerSymbol.Color = pNextUniqueColor;
                            pUniqueValueRender.AddValue(codeValue.ToString(), "", pMarkerSymbol as ISymbol);//添加渲染字段的值和渲染样式
                            pNextRow = pCursor.NextRow();
                            break;
                        }
                }

                // 分级渲染
                ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                int IbreakIndex;
                object dataFrequency;
                object dataValues;
                //获得要着色的图层             
                ITable pTable2 = pGeoFeatLyr.FeatureClass as ITable;
                ITableHistogram pTableHistogram = new BasicTableHistogramClass();
                IBasicHistogram pBasicHistogram = (IBasicHistogram)pTableHistogram;
                pTableHistogram.Field = sFieldName;
                pTableHistogram.Table = pTable2;
                pBasicHistogram.GetHistogram(out dataValues, out dataFrequency);//获取渲染字段的值及其出现的频率
                //分级方法，用于根据获得的值计算得出符合要求的数据           
                IClassifyGEN pClassify = new EqualIntervalClass();
                try
                {
                    pClassify.Classify(dataValues, dataFrequency, ref numclasses);//根据获取字段的值和出现的频率对其进行等级划分 
                }
                catch (Exception ex)
                {
                }
                //返回一个数组
                double[] Classes = (double[])pClassify.ClassBreaks;
                int ClassesCount = Classes.GetUpperBound(0);
                ILegendInfo pLegendInfo = new ClassBreaksRendererClass();
                pLegendInfo.SymbolsAreGraduated = true;
                IClassBreaksRenderer pClassBreakRenderer = pLegendInfo as IClassBreaksRenderer;
                pClassBreakRenderer.Field = sFieldName;// 设置分级字段
                //设置着色对象的分级数目
                pClassBreakRenderer.BreakCount = ClassesCount;//设置分级数目   自己改的
                pClassBreakRenderer.SortClassesAscending = true;//升序排列
                //需要注意的是分级着色对象中的symbol和break的下标都是从0开始
                double symbolSizeOrigin = 5.0;
                if (ClassesCount <= 5)
                {
                    symbolSizeOrigin = 12;
                }
                if (ClassesCount < 10 && ClassesCount > 5)
                {
                    symbolSizeOrigin = 7;
                }
                IFillSymbol pBackgroundSymbol = new SimpleFillSymbolClass(); //另外添加（这个在分级符号中也得添加）
                pBackgroundSymbol.Color = m_OperateMap.GetRgbColor(255, 255, 100);
                for (IbreakIndex = 0; IbreakIndex <= ClassesCount - 1; IbreakIndex++)
                {
                    pClassBreakRenderer.set_Break(IbreakIndex, Classes[IbreakIndex + 1]);
                    pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                    pSimpleMarkerSymbol.Color = m_OperateMap.GetRgbColor(255, 100, 100);
                    pClassBreakRenderer.BackgroundSymbol = pBackgroundSymbol;// 另外添加（这个在分级符号中也得添加）
                    pSimpleMarkerSymbol.Size = symbolSizeOrigin + IbreakIndex * symbolSizeOrigin / 3.0d;
                    pClassBreakRenderer.set_Symbol(IbreakIndex, (ISymbol)pSimpleMarkerSymbol);
                }
                IScaleDependentRenderer pScaleDependentRenderer = new ScaleDependentRendererClass();
                pScaleDependentRenderer.AddRenderer(pUniqueValueRender as IFeatureRenderer);
                pScaleDependentRenderer.AddRenderer(pClassBreakRenderer as IFeatureRenderer);
                pScaleDependentRenderer.set_Break(0, 20000000);
                pScaleDependentRenderer.set_Break(1, 40000000);
                pGeoFeatLyr.Renderer = (IFeatureRenderer)pScaleDependentRenderer;
                mainMapControl.ActiveView.Refresh();
                axTOCControl1.Update();
            }
        }
        #endregion

        #region 要素编辑
        private void 几何元素示例ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            几何元素示例 pElementEditDemo = new 几何元素示例();
            pElementEditDemo.ShowDialog();
        }

        private void 开始编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                pMap = mainMapControl.Map;
                pActiveView = pMap as IActiveView;
                plstLayers = MapManager.GetLayers(pMap);
                if (plstLayers == null || plstLayers.Count == 0)
                {
                    MessageBox.Show("请加载编辑图层！", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                pMap.ClearSelection();
                pActiveView.Refresh();
                //InitComboBox(plstLayers);
                ChangeButtonState(true);
                //如果编辑已经开始，则直接退出
                if (pEngineEditor.EditState != esriEngineEditState.esriEngineStateNotEditing)
                    return;
                if (pCurrentLyr == null) return;
                //获取当前编辑图层工作空间
                IDataset pDataSet = pCurrentLyr.FeatureClass as IDataset;
                IWorkspace pWs = pDataSet.Workspace;
                //设置编辑模式，如果是ArcSDE采用版本模式
                if (pWs.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                {
                    pEngineEditor.EditSessionMode = esriEngineEditSessionMode.esriEngineEditSessionModeVersioned;
                }
                else
                {
                    pEngineEditor.EditSessionMode = esriEngineEditSessionMode.esriEngineEditSessionModeNonVersioned;
                }
                //设置编辑任务
                pEngineEditTask = pEngineEditor.GetTaskByUniqueName("ControlToolsEditing_CreateNewFeatureTask");
                pEngineEditor.CurrentTask = pEngineEditTask;// 设置编辑任务
                pEngineEditor.EnableUndoRedo(true); //是否可以进行撤销、恢复操作
                pEngineEditor.StartEditing(pWs, pMap); //开始编辑操作
            }
            catch (Exception ex)
            {
            }
        }

        

        private void ChangeButtonState(bool bEnable)
        {
            btnStartEdit.Enabled = !bEnable;
            btnSaveEdit.Enabled = bEnable;
            btnEndEdit.Enabled = bEnable;

            
        }

        private void InitObject()
        {
            try
            {
                ChangeButtonState(false);
                pEngineEditor = new EngineEditorClass();
                MapManager.EngineEditor = pEngineEditor;
                pEngineEditTask = pEngineEditor as IEngineEditTask;
                pEngineEditLayers = pEngineEditor as IEngineEditLayers;
            }
            catch (Exception ex)
            {

            }
        }
        #endregion

        #region GP工具

        private void 缓冲区分析ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            
        }

        private void shapefile转CADToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmShapeToCAD pFrmShapeToCAD = new FrmShapeToCAD(this.mainMapControl);
            pFrmShapeToCAD.ShowDialog();
            if (pFrmShapeToCAD.DialogResult == DialogResult.OK)
            {
                this.mainMapControl.Refresh();
                this.mainMapControl.Refresh();
            }
        }

        private void 计算坡向ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Geoprocessor gp = new Geoprocessor();
            gp.OverwriteOutput = true;
            ESRI.ArcGIS.Analyst3DTools.Aspect pAspect = new ESRI.ArcGIS.Analyst3DTools.Aspect();
            ILayer pLayer = this.mainMapControl.get_Layer(0);
            IRasterLayer featLayer = pLayer as IRasterLayer;
            pAspect.in_raster = featLayer;
            pAspect.out_raster = @"E:\\aaa.tif";
            gp.Execute(pAspect, null);
        }
        #endregion
    }

}